1

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

0

3 Answers 3

3

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 (e.g., altering arrayT['two']['a'] on the next line will alter arrayT['one']['a'], since they point to the same object).

Sign up to request clarification or add additional context in comments.

Comments

3

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();

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.