Undesired results when populating an array from lodash fill vs regular array

北慕城南 提交于 2019-12-11 11:00:45

问题


Question, is _.fill(Array(4), []) equal to [[], [], [], []]?

Because _.isEqual(_.fill(Array(4), []), [[], [], [], []]) is true

var test = [[], [], [], []];
test[0].push(1);
console.log(test[0]);
test[1].push(2);
console.log(test[1]);
test[2].push(3);
console.log(test[2]);
test[3].push(4);
console.log(test[3]);

returns

[1]
[2]
[3]
[4]

which is I wanted, but

var test = _.fill(Array(4), []);
test[0].push(1);
console.log(test[0]);
test[1].push(2);
console.log(test[1]);
test[2].push(3);
console.log(test[2]);
test[3].push(4);
console.log(test[3]);

returns

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]

Am I doing it wrong? I wanted to create and populate an array of arrays in which the 4 in _.fill(Array(4), []) is dynamic.


回答1:


[] is equivalent to new Array() in JS.

This means that [[], [], [], []] is an array with 4 new arrays, and _.fill(Array(4), []) is an array containing four copies of the same array.

In other words, the _.fill variant is equivalent to:

var a = [];
var test = [a, a, a, a];

If you want to make a multidimensional array, you can do:

_.map(Array(n), function () { return []; })

to create a 2-dimensional array.



来源:https://stackoverflow.com/questions/32349148/undesired-results-when-populating-an-array-from-lodash-fill-vs-regular-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!