问题
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