Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

javascript - Changing one cell in multidimensional array updates entire column

When creating a new multidimensional array in Chrome's console like this:

var array = Array(10).fill(Array(10).fill(false));

the array looks as expected (inspect with console.table): enter image description here

But when trying to change only one cell in the array: array[5][5] = true; something strange happens: enter image description here

I have been banging my head against the wall for sometime because of this, but can't figure it out. Could this be a bug since Array.fill is an experimental/new feature?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's because you actually only created two arrays. You created an inner array with 10 elements and then an outer array that has 10 elements, each of which reference the same inner array. When you change an element of the inner array and then look at the outer array, you'll see the same change in the inner array repeated 10 times.

Create your outer array with a loop instead so that a new inner array is created for every element of your outer loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...