简体   繁体   English

JavaScript二维数组

[英]JavaScript 2dimensional array

I have following 我有以下

    var arrayT = new Array();
    arrayT['one'] = arrayT['two'] = new Array();
    arrayT['one']['a'] = arrayT['one']['b'] = '';
    arrayT['two'] = arrayT['one'];
    arrayT['two']['a'] = 'test';
    console.log(arrayT);

In console I have 在控制台中,我有

    [one][a]='test'
    [one][b]=''
    [two][a]='test'
    [two][b]=''

Why? 为什么?

jsFiddle jsFiddle

The line 线

arrayT['one'] = arrayT['two'] = new Array();

creates a single shared array object . 创建一个共享数组对象 Each "inner" array in your two-dimensional array is really just a reference to the same object, so altering one "inner" array will necessarily affect the other in the exact same way. 二维数组中的每个“内部”数组实际上只是对同一对象的引用,因此更改一个“内部”数组将必然以完全相同的方式影响另一个。

Instead, create two separate arrays: 而是创建两个单独的数组:

arrayT['one'] = new Array();
arrayT['two'] = new Array();

Futhermore , even if you implement that change, the line: 此外 ,即使您实施了该更改,该行也会:

arrayT['two'] = arrayT['one'];

will create the same problem -- arrayT['two'] and arrayT['one'] will point to the same object, possibly causing future problems of a similar nature (eg, altering arrayT['two']['a'] on the next line will alter arrayT['one']['a'] , since they point to the same object). 会产生相同的问题arrayT['two']arrayT['one']将指向同一对象,可能会导致类似性质的未来问题(例如,更改arrayT['two']['a']在下一行将更改arrayT['one']['a'] ,因为它们指向同一对象)。

arrayT['one'] and arrayT['two'] are the same array, any change you make to one will affect the other. arrayT['one']arrayT['two']是同一数组,您对其中一个所做的任何更改都会影响另一个。

To fix this, create separate arrays: 要解决此问题,请创建单独的数组:

arrayT['one'] = new Array();
arrayT['two'] = new Array();

This issue of multiple references to the same array happens when you use arrayT['one'] = arrayT['two'] = new Array() , but arrayT['two'] = arrayT['one'] will create the same issue. 当您使用arrayT['one'] = arrayT['two'] = new Array() ,会发生对同一数组的多个引用的问题,但是arrayT['two'] = arrayT['one']将创建相同的arrayT['two'] = arrayT['one']问题。 To make arrayT['two'] a copy of arrayT['one'] you should use the following: 要使arrayT['two']成为arrayT['one']的副本,您应该使用以下命令:

arrayT['two'] = arrayT['one'].slice();

While apsillers is right with his answer, a more accurate replacement would be to simply write arrayT['two'] = arrayT['one'].slice(0) leaving out the assignment to arrayT['two'] in line 2. Note, that this is only a shallow copy. 虽然apsillers的回答是正确的,但更准确的替代方法是只写arrayT['two'] = arrayT['one'].slice(0)arrayT['two']第2行中对arrayT['two']的分配。注意,这只是一个浅表副本。 Depending on your needs you might need to do a deep copy, if you should decide to use mutable objects later. 如果您以后决定使用可变对象,则可能需要根据需要进行深度复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM