Ying Style
Ying Style

Reputation: 750

Add a new value to an existing array in JavaScript

I have defined an Array List in JavaScript:

var arrListContainer = [];
var emptyArray = [];
for (var i = 0; i < 5; ++i) {
    arrListContainer.push(emptyArray);
}

The default value of list is: [[], [], [], [], []]

I want to add value to arrListContainer[2], so:

arrListContainer[2].push("a");

Why the result is [["a"], ["a"], ["a"], ["a"], ["a"]]?

I don't understand. I just need [[], [], ["a"], [], []]

Thank you!

Upvotes: 2

Views: 612

Answers (3)

catlovespurple
catlovespurple

Reputation: 702

var arrListContainer = [];
var emptyArray = [];


for (var i = 0; i < 5; ++i) {
    var emptyArray = [];
    if(i === 2){
        emptyArray.push("a");
    }
    arrListContainer.push(emptyArray);
}


for(var i=0; i< 5; ++i){
    console.log(arrListContainer[i]);
}

is this what you want? Try it out in your js file or jsfiddle and take a look at the results from console.

Upvotes: 0

akiller
akiller

Reputation: 2472

You're pushing the same emptyArray instance into each arrListContainer element during the initialisation. So when you later push "a" into the second index of it you're effecting the rest of the elements because they all contain the same emptyArray item.

If you change your code to the below, where you don't re-use the same emptyArray variable it works:

var arrListContainer = [];
for (var i = 0; i < 5; ++i) {
    arrListContainer.push([]);
}
arrListContainer[2].push("a");

Upvotes: 1

Paul S.
Paul S.

Reputation: 66404

You're making each index in arrListContainer point to the same object instance, you'll need to create new emptyArrays inside your loop (or just push a literal directly)

var arrListContainer = [], i;
for (i = 0; i < 5; ++i) {
    arrListContainer.push([]);
}

If you want more clarity, the way you were doing is similar to this

var foo = [],
    bar = foo;
foo[2] = 'baz';
// what is bar[2]?
bar[2]; // "baz"
// because
foo === bar; // true

Upvotes: 7

Related Questions