从lodash fill和regular数组填充数组时出现不需要的结果 [英] Undesired results when populating an array from lodash fill vs regular array
问题描述
问题,是 _。fill(Array(4),[])
等于 [[],[],[],[ ]]
?
因为 _。isEqual(_。fill(Array(4),[]),[ [],[],[],[]])
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]);
返回
[1]
[2]
[3]
[4]
这是我想要的,但是
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]);
返回
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
我做错了吗?我想创建并填充一个数组数组,其中 4
在 _。fill(Array(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.
推荐答案
[]
相当于< JS中的code> new Array()。
这意味着 [[],[], [],[]]
是一个包含4个新数组的数组,而 _。fill(Array(4),[])
是一个数组包含相同数组的四个副本。
This means that [[], [], [], []]
is an array with 4 new arrays, and _.fill(Array(4), [])
is an array containing four copies of the same array.
换句话说, _ .fill
变体相当于:
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 []; })
创建一个二维数组。
这篇关于从lodash fill和regular数组填充数组时出现不需要的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!