简体   繁体   中英

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!

You're making each index in arrListContainer point to the same object instance, you'll need to create new emptyArray s 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

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");
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.

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