在 javascript 中迭代整数,其中每个值等于一位数字

问题描述 投票:0回答:2

我想使用

$.each()
循环来迭代整数中的数字。 该整数是作为另一个数组的索引生成的,尽管我不确定这是否会产生影响。

Javascript

var words = [ "This", "is", "an", "array", "of", "words","with", "a", "length", "greater", "than", "ten." ];
var numbers = [];
$.each(words, function(i,word) {
    $.each(i, function(index,value) {
        $(numbers).append(value);
    });
});

我希望数组

numbers
等于以下数组:

[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1 ]

最后四个条目

[ ... 1, 0, 1, 1 ]
是通过迭代
[ ... "than", "ten." ]
数组中条目
words
的索引生成的。

javascript arrays loops integer iteration
2个回答
2
投票

let words = [ "This", "is", "an", "array", "of", "words","with", "a", "length", "greater", "than", "ten." ];

let numbers = words.map((w, i) => i.toString().split('').map(Number)) //map into array of digits
    numbers = Array.prototype.concat.call(...numbers); //concat them all
 console.log(numbers);


0
投票

单词本身在输出中不起任何作用,因此输入实际上只是长度。您可以在此处使用

flatMap
迭代器助手:

// The input really is only a length:
const n = 12;
const digits = n => Array.from(n+"", Number);
const numbers = Array(n).keys().flatMap(digits).toArray();
    
console.log(...numbers);

© www.soinside.com 2019 - 2024. All rights reserved.