2

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!

H. Pauwelyn
14.4k28 gold badges93 silver badges164 bronze badges
asked Aug 15, 2015 at 16:57
2
  • Can you replicate your problem into a snippet or create a jsfiddle? Commented Aug 15, 2015 at 17:00
  • Try doing like this: arrListContainer.push([]); Commented Aug 15, 2015 at 17:01

3 Answers 3

7

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
answered Aug 15, 2015 at 17:00
Sign up to request clarification or add additional context in comments.

Comments

1

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");
answered Aug 15, 2015 at 17:03

Comments

0
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.

answered Aug 15, 2015 at 17:06

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.