2017-08-28 60 views
3

我有一個包含四個元素的數組,我想將它複製到另一個數組四次,並且通過連接四次完成它。將陣列N次複製到分層陣列

我的努力

let demoProperties = [] 
    .concat(fourDemoProperties) 
    .concat(fourDemoProperties) 
    .concat(fourDemoProperties) 
    .concat(fourDemoProperties); 

我也跟着另一個way(映射,減少),但這種方式迭代兩次。

有沒有任何最簡單的方法複製N次?任何你的建議將不勝感激。

回答

4

您可以使用傳播語法:

const demoProperties = [...fourDemoProperties, ...fourDemoProperties, ...fourDemoProperties, ...fourDemoProperties]; 

或者使用陣列#填充複製的數組,然後使用傳播語法使用Array#CONCAT得到一個新的數組:

const fourDemoProperties = [1, 2, 3, 4]; 
 

 
const demoProperties = [].concat(...Array(4).fill(fourDemoProperties)); 
 

 
console.log(demoProperties);

注意:手冊和Array#填充都是淺層克隆。如果項目是對象,則將克隆對象的引用,如果要更改其中一個對象,則「副本」也會更改。

例(檢查瀏覽器的控制檯):

const fourDemoProperties = [{ a: 1 }, { b: 2 }]; 
 

 
const demoProperties = [...fourDemoProperties, ...fourDemoProperties, ...fourDemoProperties, ...fourDemoProperties]; 
 

 
demoProperties[0].a = 5000; 
 

 
console.log(demoProperties);

1

如何你,如果你想保留的子陣列或無法躋身參考做到這一點依賴。

var ar = [1,2,3,4], 
 
    ars = Array.from({length:4}).map(_ => ar), 
 
    brs = Array.from({length:4}).map(_ => ar.slice()); 
 
console.log(ars); 
 
console.log(brs);