在JavaScript中,如何以简洁的方式重复包含多个元素的数组?

在Ruby中,您可以

irb(main):001:0> ["a", "b", "c"] * 3
=> ["a", "b", "c", "a", "b", "c", "a", "b", "c"]

我查找了lodash库,没有找到任何直接适用的库。 Feature request: repeat arrays.是一项功能请求,用于将其添加到lodash,并且给出的最佳解决方法是
const arrayToRepeat = [1, 2, 3];
const numberOfRepeats = 3;
const repeatedArray = _.flatten(_.times(numberOfRepeats, _.constant(arrayToRepeat)));

问题Most efficient way to create a zero filled JavaScript array?Create an array with same element repeated multiple times专​​注于仅重复单个元素多次,而我想重复包含多个元素的数组。

使用合理维护良好的库是可以接受的。

最佳答案

不需要任何库,可以使用Array.from创建要重复的数组数组,然后使用[].concat展平并传播:

const makeRepeated = (arr, repeats) =>
  [].concat(...Array.from({ length: repeats }, () => arr));

console.log(makeRepeated([1, 2, 3], 2));


在较新的浏览器上,可以使用Array.prototype.flat而不是[].concat(...:

const makeRepeated = (arr, repeats) =>
  Array.from({ length: repeats }, () => arr).flat();

console.log(makeRepeated([1, 2, 3], 2));

09-05 02:12
查看更多