javascript - 将数组 N 次复制到扁平数组

标签 javascript arrays

我有一个包含四个元素的数组,我想将它复制到另一个数组四次,我通过连接四次来完成。

我的努力

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

我还关注了另一个way (映射和减少)但这种方式迭代两次。

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

最佳答案

你可以使用传播语法:

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

关于javascript - 将数组 N 次复制到扁平数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45917564/

相关文章:

Javascript 测验结果计算/生成

php - PHP 中的数组是作为值复制还是作为对新变量的引用,以及何时传递给函数?

c++ - 将数组本地抛出到 try block

javascript - 向文本溢出 : ellipsis 的元素添加标题属性

php - Firefox 弹出窗口不会接收 cookie

javascript - Backbone Marionette 相关模型

javascript - 在嵌入式 V8 引擎中调试 JavaScript

javascript - 该脚本无缘无故地禁用左键单击

javascript - 在javascript中使用外键访问数组属性

c - 如何将结构数组的地址传递给函数?