Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Strange behavior of an array filled by Array.prototype.fill()

I face something I don't understand with an array. Indeed, I created an array I have filled with empty subArrays to obtain a 2D Matrix. But when I manipulate the array it doesn't behave as I expected.

var arr = new Array(5);
arr.fill([]);
arr[2].push("third rank item");
console.log(arr);

//[ [ 'third rank item' ],
//  [ 'third rank item' ],
//  [ 'third rank item' ],
//  [ 'third rank item' ],
//  [ 'third rank item' ] ]

Every lights on this matter will be welcomed

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is the same old problem with arrays (and objects in general) being references rather than values.

Specifically, when you do arr.fill([]), you are taking that one single empty array and using that to fill the parent one.

It's like saying:

var arr = new Array(5);
arr[0] = arr[1] = arr[2] = arr[3] = arr[4] = [];

They all refer to the same array! So when you then go on to modify one of them, it looks like they're all modified (but really it's still the same one)

Unfortunately there's no simple way to assign an empty array to each one. You could do something like:

Array.apply(null, Array(5)).map(function() {return [];});

Essentially, create an (initialised) empty array of length 5 and map each (empty) value to a new [].

EDIT: Seems like I'm stuck in old times. As per @torazaburo's comment, you can use Array.from instead of Array.apply(null, Array(5)).map, like so:

Array.from( new Array(5), function() { return []; } );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...