javascript - 数组上的链接方法显示为未定义

标签 javascript arrays method-chaining

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/

相关文章:

javascript - 表单验证中的错误消息未按预期显示

javascript - Bootstrap 按钮 onclick 不起作用

javascript - Angular 异步管道卡在 promise 上

javascript - jQuery/JSON 数据不在创建的 HTML 中循环

java - 为什么不能将 Object[] 转换为 String[]

javascript - Dojo 如何混合两个数组?

javascript - 如何从javascript中的对象获取特定的键值?

javascript - JS – 三元运算符,以避免条件中的过度链接。是否可以?

python - pandas 中的条件方法链接

swift - Swift 中的方法和属性链接调用