Help? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Help?

I am confused about why this part of my code is creating an array inside of an array inside of another array when I only wanted an array inside of an array. Can anyone explain why this is happening? var array = [] var x = 5; var y = 5; var placeholder = []; for(var repeatIndex = 0; repeatIndex < x; repeatIndex++) { placeholder.push(0) console.log(placeholder) } console.log(placeholder) for(var repeatIndex = 0; repeatIndex < y; repeatIndex++) { array.push(placeholder) console.log(array) } Console log: [0] 0: 0 1: 0 2: 0 3: 0 4: 0 (2) [0,0] 0: 0 1: 0 2: 0 3: 0 4: 0 (3) [0, 0, 0] 0: 0 1: 0 2: 0 3: 0 4: 0 (4) [0, 0, 0, 0] 0: 0 1: 0 2: 0 3: 0 4: 0 (5) [0, 0, 0, 0, 0] 0: 0 1: 0 2: 0 3: 0 4: 0 (5) [0, 0, 0, 0, 0] 0: 0 1: 0 2: 0 3: 0 4: 0 [Array(5)] 0: (5) [0, 0, 0, 0, 0] 1: (5) [0, 0, 0, 0, 0] 2: (5) [0, 0, 0, 0, 0] 3: (5) [0, 0, 0, 0, 0] 4: (5) [0, 0, 0, 0, 0] (2) [Array(5), Array(5)] 0: (5) [0, 0, 0, 0, 0] 1: (5) [0, 0, 0, 0, 0] 2: (5) [0, 0, 0, 0, 0] 3: (5) [0, 0, 0, 0, 0] 4: (5) [0, 0, 0, 0, 0] (3) [Array(5), Array(5), Array(5)] 0: (5) [0, 0, 0, 0, 0] 1: (5) [0, 0, 0, 0, 0] 2: (5) [0, 0, 0, 0, 0] 3: (5) [0, 0, 0, 0, 0] 4: (5) [0, 0, 0, 0, 0] (4) [Array(5), Array(5), Array(5), Array(5)] 0: (5) [0, 0, 0, 0, 0] 1: (5) [0, 0, 0, 0, 0] 2: (5) [0, 0, 0, 0, 0] 3: (5) [0, 0, 0, 0, 0] 4: (5) [0, 0, 0, 0, 0] (5) [Array(5), Array(5), Array(5), Array(5), Array(5)] 0: (5) [0, 0, 0, 0, 0] 1: (5) [0, 0, 0, 0, 0] 2: (5) [0, 0, 0, 0, 0] 3: (5) [0, 0, 0, 0, 0] 4: (5) [0, 0, 0, 0, 0] You can try this yourself, you would get the same result if you put in the code

23rd Feb 2021, 5:19 PM
EpsilAnt
EpsilAnt - avatar
1 Answer
0
it looks like the code is functioning correctly. What you have is an array with multiple copies of another array inside it. It is not an array inside of another array inside of a third array.
23rd Feb 2021, 6:53 PM
Wilbur Jaywright
Wilbur Jaywright - avatar