本文介绍了为什么这两个 javascript 二维数组的行为不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的函数中,我定义了两个数组,第一个 (array1) 具有预先初始化的长度.我添加了第二个数组 (array2) 只是为了测试,因为我认为第一个数组的行为很奇怪.

In my function, I have defined two arrays, the first (array1), has a pre-initialized length. I added the second array (array2) just for testing because I thought the first was behaving strangely.

我的代码:

function test(n = 3) {
  array1 = new Array(n).fill(new Array(n));
  array2 = [
    [undefined, undefined, undefined],
    [undefined, undefined, undefined],
    [undefined, undefined, undefined]
  ];

  document.getElementById("output").innerHTML = JSON.stringify(array1) + " (array 1) <br/>" + JSON.stringify(array2) + " (array 2)<br/><br/><hr/>";


  for (i = 0; i < n; i++) {
    array1[i][0] = i;
    array2[i][0] = i;
  }

  document.getElementById("output").innerHTML += JSON.stringify(array1) + " (array 1) <br/>" + JSON.stringify(array2) + " (array 2)<br/><br/><hr/>";

}
<button onclick="test();">Press to test</button>

<br/><br/>
<div id="output"></div>

for 循环中,我尝试更改第二个维度的第一个值.它应该输出 [[0, undefined, undefined], [1, undefined, undefined], [2, undefined, undefined]],就像第二个数组一样.

In the for loop, I try to change the first value of the second dimensions. It should output [[0, undefined, undefined], [1, undefined, undefined], [2, undefined, undefined]], like the second array does.

我的问题是:为什么会发生这种情况?而且,我怎样才能在两个维度上创建一个长度为 n 的预初始化数组,它的行为类似于第二个数组?

My questions are: why does this happen? And, how can I make a pre-initialized array with length n in both dimensions, that behaves like the second array?

推荐答案

因为 Array.fill

fill() 方法用静态值填充数组从开始索引到结束索引的所有元素.

接受一个静态值并用它填充数组.因此,您在 array1 的每个元素中都获得了相同的填充数组.

takes a static value and fills the array with it. Therefore you get in every element of array1 the same array of the filling.

function test(n = 3) {
    var array1 = new Array(n).fill(new Array(n)),
        array2 = [[undefined, undefined, undefined], [undefined, undefined, undefined], [undefined, undefined, undefined]],
        i;

    for (i = 0; i < n; i++) {
        array1[i][0] = i;
        array2[i][0] = i;
    }

    document.getElementById("output").innerHTML = array1 + " (array 1) <br/>" + array2 + " (array 2)<br/><br/><i>The commas with nothing in between mean undefined.</i>";
    console.log(array1);
    console.log(array2);
}
<button onclick="test();">Press to test</button><br/><br/>
<div id="output"></div>

要获得独立的填充数组,您可以使用 Array.from 并用映射值映射一个新数组.

To get an independent filled array, you could use Array.from and map a new array with mapped values.

var array = Array.from({ length: 3 }, _ => Array.from({ length: 3 }, _ => 4));

array[0][0] = 0;
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于为什么这两个 javascript 二维数组的行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:00