为什么对单元格所做的更改会传播到使用fill创建的这个二维数组中的其他单元格?

编程入门 行业动态 更新时间:2024-10-19 00:24:28
本文介绍了为什么对单元格所做的更改会传播到使用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创建的这个二维数组中的其他单元格?

本文发布于:2023-11-29 21:37:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647692.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元格   所做   组中   fill

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!