简体   繁体   中英

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

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['one'] and arrayT['two'] are the same array, any change you make to one will affect the other.

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. To make arrayT['two'] a copy of arrayT['one'] you should use the following:

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. Depending on your needs you might need to do a deep copy, if you should decide to use mutable objects later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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