javascript - Array.fill 与赋值时的文字 2D 定义不同

标签 javascript arrays

之前我一直在尝试 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.

更新: 这实际上为我开辟了一条好方法,让我可以学习一些我宁愿知道但不遵守原因或方式的东西。然而,我认为这个问题现在将更广泛地针对“程序员”,而不是编码本身。

最佳答案

参见Array.prototype.fill()

The fill method is a mutable method, it will change this object itself, and return it, not just return a copy of it.

解决方法可能是使用 forwhile 循环

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/

相关文章:

javascript - 如何从子组件更改父状态?

javascript - fullpage.js 与 mobile.js 和 camera.js 的不兼容问题

javascript - 在 API 中使用 JavaScript Promise

arrays - 比较字符串与字符串数组

php - 使用 php 数组创建 mysql 查询

php - 如何在数组中添加数据

javascript - 如何检查变量是否是javascript中的类型化数组?

javascript - 如果不刷新,我的代码将无法工作。它没有显示正确的页面颜色

jquery - 将更多对象数组添加到本地存储键中

C++ 用派生自数组类型的对象填充数组