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

Chaining methods on array display as undefined

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.

问题是forEachreturnsundefined

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); 
});

您想生成由 9 个数组组成的数组,其中填充了 0 并且 return 将其设置为变量。

您可以使用 map 方法实现此目的。

const array = 
  new Array(9)
      .fill([])
      .map(function(){
        return Array(9).fill(0);
       });     
       
console.log(array);   

p.s。在您的案例中,不需要将值、索引等传递给映射方法参数

Array.prototype.forEachreturnsundefined。只需像下面这样调用 forEach

const array = new Array(9).fill([])
array.forEach( function(value,index,arr){
   arr[index] = Array(9).fill(0);
});
// [
//   [0, 0, 0, ...],
//   ...
// ]

使用 map 是另一种选择,但我不赞成它,因为它会在内存中创建另一个数组。

因为其他答案已经提到Array.forEach returns undefined 或没有return 任何东西,你不能使用它。

作为替代方法,您可以使用 Array.from

示例如下:

var output = Array.from({
  length: 9
}, () => {
  return Array.from({
    length: 9
  }, () => 0)
});

console.log(output)


此外,您的代码还有一个问题是,您正在使用 Array.fill 中的一个对象。 array.fill 的作用是,它会先创建要填充的值,然后将其填充到所有项目中。

var output = new Array(9).fill([]);
output[0].push(1);
console.log(output)

在你检查输出时,它显示 /**ref:2**/,但如果你在控制台中检查,你会注意到所有项目都会有项目 1。所以你应该避免使用带有 Array.fill.

的对象