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,问题是什么?
最佳答案
But what is the problem for scenario 1 where bounded forEach methods array defnitions works fine.
问题是forEach返回未定义
I woule like to define multiple dimensional arrays within one line used as this.state command.
您可以使用map
来实现相同的效果
var output = new Array(9).fill([]).map( function(value,index,arr){
return Array(9).fill(0); //return the inner array
});
或者按照@bergi的建议,您也可以使用Array.from
var output = Array.from(Array(9)).map( function(value,index,arr){
return Array(9).fill(0);
});
关于javascript - 数组上的链接方法显示为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47882960/