之前我一直在尝试 Array.fill函数,给自己创建了一个全零填充的 9x9 2D 数组,然后我想更新 [3][4] 值。嘭,第一维中每个键的所有第四个键的值都会更新([0][4],[1][4],...)。
我花了一段时间才弄清楚,但 Array.fill 的定义似乎与字面的 2D 数组定义有所不同,或者是吗?因为那是我不再确定我是否遗漏了什么的地方。
var arr1 = new Array(9).fill(new Array(9).fill(0));
arr1[3][4] = 1;
console.log(arr1);
//Every fourth key of the 2nd dimension are replaced with 1.
var arr2 = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
];
arr2[3][4] = 1;
console.log(arr2);
//Only the third key of first dimension to fourth key of 2nd is replaced with 1.
更新: 这实际上为我开辟了一条好方法,让我可以学习一些我宁愿知道但不遵守原因或方式的东西。然而,我认为这个问题现在将更广泛地针对“程序员”,而不是编码本身。
最佳答案
The fill method is a mutable method, it will change this object itself, and return it, not just return a copy of it.
解决方法可能是使用 for
、 while
循环
var arr1 = Array(9);
for (var i = 0, n = 0; i < arr1.length; i++) {
// create a new array object at index `i` of `arr1`
arr1[i] = [];
while (arr1[i].length < arr1.length) {
// fill array at index `i` of `arr1` with value of `n` : `0`
arr1[i][arr1[i].length] = n
}
}
arr1[3][4] = 1;
document.querySelector("pre").textContent = JSON.stringify(arr1, null, 2)
<pre></pre>
关于javascript - Array.fill 与赋值时的文字 2D 定义不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35180489/