JavaScript中2D数组中的值意外变化 [英] Unexpected value change in 2D array in JavaScript

查看:58
本文介绍了JavaScript中2D数组中的值意外变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修改2D数组中的一个值.但是,根据数组的构造方式,我发现了一些奇怪的行为.

I'm trying to modify one value in a 2D array. However I'm finding some weird behavior based on how the array is constructed.

matrix和matrix2之间的唯一区别是它们的构造方式.但是,当我更改[1] [1]值时,matrix2中的所有[x] [1]值都被更改了:

The only difference between matrix and matrix2 is how they're constructed. However when I change the [1][1] value, all of the [x][1] values in matrix2 are changed:

矩阵:

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

Matrix2(意外):

Matrix2 (unexpected):

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

代码:

var row = [0,0,0];
var matrix = [[0,0,0],[0,0,0],[0,0,0]];
var matrix2 = [row, row, row];
console.log(matrix);
console.log(matrix2);
matrix[1][1] = 1;
matrix2[1][1] = 1;
console.log(matrix);
console.log(matrix2);

任何人都可以解释发生了什么事吗?

Can anyone explain what's going on?

推荐答案

[row, row, row]

您刚刚创建了一个数组,其中包含三个对相同内部数组的引用.

You just made an array with three references to the same inner array.

对内部数组的更改可以通过对其的任何引用来看到.

Changes to the inner array can be seen through any reference to it.

您要创建内部数组的三个副本.
您可以通过调用.slice()创建数组的浅表副本.

You want to create three copies of the inner array.
You can create a shallow copy of an array by calling .slice().

这篇关于JavaScript中2D数组中的值意外变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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