我需要从零迭代到30,但我想使用forEach
来完成此操作:
new Array(30).forEach(console.log.bind(console);
当然这行不通,因此我这样做:
new Array(30).join(',').split(',').forEach(console.log.bind(console));
有没有其他方法来填充空数组?
我需要从零迭代到30,但我想使用forEach
来完成此操作:
new Array(30).forEach(console.log.bind(console);
new Array(30).join(',').split(',').forEach(console.log.bind(console));
有没有其他方法来填充空数组?
实际上,有一种简单的方法可以创建一个[0..N)
(不包括N
)的范围:
var range0toN = Object.keys(Array.apply(0,Array(N)));
显然,如果您只想获取一个包含N个元素的正确数组,可以不使用Object.keys
部分。
尽管如其他人所说,在这种特定情况下,最好使用for
循环。
var arrLength = 4
var arrVal = 0
var newArr = [...new Array(arrLength)].map(x => arrVal);
// result will be [0, 0, 0, 0]
for
循环。for (var i = 0; i < 30; i += 1) {
...
...
}
实际上,如果你正在寻找一种创建数字范围的方法,那么你可以这样做
console.log(Array.apply(null, {length: 30}).map(Number.call, Number));
它将创建从0到29的数字。来源:在JavaScript中创建范围-奇怪的语法
console.log(Array.apply(null, new Array(30)).map(Number.call, Number));
。长度技巧也很有趣。谢谢。 - 3y3 var index, // we use that in the for loop
counter, // number of elements in array
myArray; // the array you want to fill
counter = 30;
myArray = [];
for (index = 0; index < counter; index += 1) {
myArray[index] = [];
/*
// alternative:
myArray.push([]);
// one-liner
for (index = 0; index < counter; index += 1) myArray.push([]);
*/
}
如果你坚持使用 foreach
var data = [1, 2, 3];
data.forEach(function(x) {
console.log(x);
});