2015-09-02 26 views
1

問題是_.fill(Array(4), [])等於[[], [], [], []]從lodash填充vs普通數組填充數組時出現不希望的結果

因爲_.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是動態的一組數組。

回答

1

[]相當於JS中的new Array()

這意味着[[], [], [], []]是一個包含4個新數組的數組,而_.fill(Array(4), [])是包含相同數組的四個副本的數組。

換句話說,該_.fill變型等同於:

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

如果你想使一個多維數組,你可以這樣做:

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

創建的2-二維數組。