为什么对单元格所做的更改会传播到使用fill创建的这个二维数组中的其他单元格? [英] Why do changes made to a cell propagate to other cells in this 2 dimensional array created using fill?

查看:170
本文介绍了为什么对单元格所做的更改会传播到使用fill创建的这个二维数组中的其他单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JS中遇到这个二维数组的问题。当我更改 a [1] [0] 时, a [0] [0] 随之更改。我初始化它的方式有什么问题吗?如果是,我该如何正确初始化它?

I have a problem with this 2-dimensional array in JS. When I change a[1][0], a[0][0] changes with it. Is there something wrong in the way I am initializing it? If yes, how can I initialize it properly?

>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true


推荐答案

var a = Array(100).fill(Array(100).fill(false));

a 包含一个数组,每个元素都是它引用了一个数组。您正在使用包含所有错误值的数组填充外部数组。内部数组只进行一次,并且对同一数组的引用被传递给外部数组的每个元素,这就是为什么如果你对一个元素执行操作它也反映在其他元素上。

a contains an array, each element of which references to an array. you are filling the outer array with an array which contains all false values. The inner array is being made only once and reference to the same array is passed to each element of outer array that is why if you perform an operation on one element it reflects on other elements as well.

这实际上相当于

var a1 = Array(100).fill(false);
var a = Array(100).fill(a1);

此处 a 获取100个元素全部有参考到相同的数组 a1 。因此,如果您更改 a 中的一个元素,则所有元素都会更改,因为它们是对同一数组的引用。

here a gets 100 elements all having reference to same array a1. So if you change one element of a, all elements change since they are references to same array.

您需要使用新数组填充外部数组中的每个元素。你可以这样做:

you will need to fill each element in outer array with a new array. you can do something like this:

var a = [];
for(var i=0; i<100; i++)
  a.push(Array(100).fill(false));

这篇关于为什么对单元格所做的更改会传播到使用fill创建的这个二维数组中的其他单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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