1

I don't know why I'm seeing the below:

const sideLength = 4;
const multiArray = new Array(sideLength).fill(new Array(sideLength));
console.log(multiArray)
var counter = 1;
multiArray[3][1] = counter;
console.log('multiArray:', multiArray)

Console output:

[ [ , , ,  ], [ , , ,  ], [ , , ,  ], [ , , ,  ] ]
multiArray: [ [ , 1, ,  ], [ , 1, ,  ], [ , 1, ,  ], [ , 1, ,  ] ]

I would have expected the second line of output to be:

multiArray: [ [ , , ,  ], [ , , ,  ], [ , , ,  ], [ , 1, ,  ] ]

Why is that 1 being added to every array's index=1 element?

2 Answers 2

6

The fill() method fills all the elements of an array from a start index to an end index with a static value.

That means all elements would refer to the same array. Changing the value of of one element would change the value of all elements since they refer to the same static object

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

2 Comments

thanks for your explanation, @marvel308. could you please help me to understand why the first console.log(multiArray) in the example above also log updated array value out
thanks @marvel308. there must be something wrong with console dev tool :). image.prntscr.com/image/a6vTGz-CQWq40RFl8pbfdQ.jpg
2

You can use Array.from() to create an Array having a specific .length

const sideLength = 4;
const multiArray = Array.from({length:sideLength}, () => new Array(sideLength));
console.log(multiArray)
var counter = 1;
multiArray[3][1] = counter;
console.log('multiArray:', multiArray)

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.