将数组复制N次到一个扁平化的数组中

3

我有一个四元素的数组,想将它复制四次到另一个数组中,我通过四次拼接完成了这个任务。

我的努力

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

我也尝试了另一种方法(使用map和reduce),但这种方法需要迭代两次。
是否有更简单、更优的复制N次的方法?欢迎您提出任何建议。
2个回答

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);

注意:无论是手动还是使用Array#fill方法,都只会进行浅拷贝。如果填充的数据是对象,那么你只会拷贝这些对象的引用。如果你修改其中一个对象,那么“副本”中的内容也会被修改。

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

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);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接