为什么多次调用Array.fill会影响未引用的数组? [英] Why do multiple calls of Array.fill effect unreferenced arrays?

查看:35
本文介绍了为什么多次调用Array.fill会影响未引用的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java实例化数组的不同方法,我发现了一些有趣的行为:

Playing around with different ways of instantiating Arrays with Javascript and I noticed some interesting behavior:

matrix = Array(3).fill(Array(3).fill(0))

创建一个0值的NxN矩阵

Creates an NxN matrix of 0 values

[
  [0,0,0],
  [0,0,0],
  [0,0,0]
]

然后我尝试将矩阵的第一行更改为全1:

I then tried changing the first row of the matrix to be all 1's:

matrix[0].fill(1)

出于某种原因将矩阵中的所有值都设为1:

Which for some reason turned ALL values in the matrix to 1's:

[
  [1,1,1],
  [1,1,1],
  [1,1,1]
]

这种行为对我来说没有意义.不仅第一行会受到对Array.fill的最终调用的影响吗?这是怎么回事?

This behavior doesn't make sense to me. Shouldn't only the first row be affected by the final call to Array.fill? What's going on here?

推荐答案

您的代码等同于

let row = [0,0,0]
let matrix = [row, row, row];
row.fill(1);

因为 .fill(Array(3).fill(0))调用 Array(3).fill(0)一次即可获得填充值-如果fill参数是一个回调,然后将为矩阵中的每个项目调用它-但是fill参数是一个值

because .fill(Array(3).fill(0)) calls Array(3).fill(0) once to get the fill value - if the fill argument were a callback, then it would call it for each item in matrix - but the fill argument is a value

在javascript中,数组被称为引用

In javascript, arrays are said to be a reference

var a = [1,2,3], b=a;
b[0] = 4

将同时导致 a b 引用具有值 [4,2,3]

will result in both a and b referencing an array with values [4,2,3]

因此,由于每个 row 是相同的数组,因此您的结果将如您所见

so, since each row is the same array, your result is as you've seen

改为尝试

const matrix = Array.from({length:3}, () => Array(3).fill(0))
matrix[0].fill(1);
console.log(matrix);

以上等同于

const matrix = [Array(3).fill(0), Array(3).fill(0), Array(3).fill(0)];
matrix[0].fill(1);

现在矩阵中的每个条目都是一个不同的数组,每次都不相同

Now each entry in matrix is a different Array, not the same one each time

这篇关于为什么多次调用Array.fill会影响未引用的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆