将数组复制N次到一个平面阵列

时间:2017-08-28 11:08:40

标签: javascript arrays

我有四个元素的数组,我想将它复制到另一个数组四次,我已经连接了四次。

我的努力

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

我还跟着另一个way(map和reduce),但这种方式迭代了两次。

有没有最简单的最佳方式复制N次?您的任何建议将不胜感激。

2 个答案:

答案 0 :(得分:4)

您可以使用扩展语法:

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

或者使用Array#fill复制数组,然后使用带有Array#concat的扩展语法来获取新数组:



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

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

console.log(demoProperties);




注意:手册和数组#fill都是浅克隆。如果这些项目是对象,您将克隆对象的引用,如果您更改其中一个,则复制"复制"也将改变。

示例(查看浏览器的控制台):



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

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

demoProperties[0].a = 5000;

console.log(demoProperties);




答案 1 :(得分: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);