我想使用
$.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
的索引生成的。
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);
单词本身在输出中不起任何作用,因此输入实际上只是长度。您可以在此处使用
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);