【发布时间】:2017-12-19 08:41:28
【问题描述】:
const array = new Array(9).fill([]).forEach(function(value, index, arr) {
arr[index] = Array(9).fill(0);
console.log(index, arr[index]); // This line report properly by creating
}); // new array.
console.log(array); // Reported as underdefined.
但是,如果重新定义如下,它会按预期工作。
const array = new Array(9).fill([]);
array.forEach( function(value,index,arr){
arr[index] = Array(9).fill(0);
console.log(index,arr[index]);
});
console.log(array);
我想在一行中定义多维数组用作此状态命令。
但是对于有界 forEach 方法数组定义工作正常的场景 1 有什么问题?
【问题讨论】:
-
forEach返回undefined -
如果您的意图是修改数组的内容,您可能需要使用
Array#map,它会返回新数组developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
注意: Array.fill 将首先创建值并在所有项目中复制相同的值。所以在这段代码
new Array(9).fill([])中,所有9个项目都将指向同一个数组 -
@apokryfos 按照规范ecma-international.org/ecma-262/6.0/… ...它返回
undefined...几乎相当于没有return声明。 -
使用
.map做一行。同意@user184994 !!
标签: javascript arrays method-chaining