This question already has answers here:
How to duplicate elements in a js array?

(11个答案)


去年关闭。




所以我想复制数组元素,例如:
var array = ["chicken","nugget","good"];

变成:
var array2 = ["chicken","chicken","nugget","nugget","good","good"];

怎么做呢?

最佳答案

惯用的方式是:

["chicken","nugget","good"].flatMap((x) => [x, x]);

请注意,并非所有的javascript环境都提供flatMap,因此可能需要进行翻译。

关于javascript - 如何在Node.js中复制数组的元素? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58513242/

10-10 11:37