在JavaScript中多次重复多个元素的数组
在JavaScript中,如何以简洁的方式重复包含多个元素的数组?
In JavaScript, how can I repeat an array which contains multiple elements, in a concise manner?
在Ruby中,你可以做到
In Ruby, you could do
irb(main):001:0> ["a", "b", "c"] * 3
=> ["a", "b", "c", "a", "b", "c", "a", "b", "c"]
我查了一下lodash库,但找不到任何直接适用的东西。 功能请求:重复数组。是将其添加到lodash的功能请求,并且是最好的给出的解决方法
I looked up the lodash library, and didn't find anything that was directly applicable. Feature request: repeat arrays. is a feature request for adding it to lodash, and the best workaround given there is
const arrayToRepeat = [1, 2, 3];
const numberOfRepeats = 3;
const repeatedArray = _.flatten(_.times(numberOfRepeats, _.constant(arrayToRepeat)));
问题最有效的方法来创建一个零填充的JavaScript数组?和创建一个多次重复相同元素的数组专注于多次重复单个元素,而我想重复一次具有多个元素的数组。
The questions Most efficient way to create a zero filled JavaScript array? and Create an array with same element repeated multiple times focus on repeating just a single element multiple times, whereas I want to repeat an array which has multiple elements.
使用维护合理的库是可以接受的。
Using reasonably well-maintained libraries is acceptable.
不需要任何库,你可以使用 Array.from
创建一个你想重复的数组数组,然后使用展平[] .concat
和点差:
No need for any library, you can use Array.from
to create an array of arrays you want repeated, and then flatten using [].concat
and spread:
const makeRepeated = (arr, repeats) =>
[].concat(...Array.from({ length: repeats }, () => arr));
console.log(makeRepeated([1, 2, 3], 2));
在较新的浏览器上,您可以使用 Array.prototype.flat
而不是 [] .concat(...
:
On newer browsers, you can use Array.prototype.flat
instead of [].concat(...
:
const makeRepeated = (arr, repeats) =>
Array.from({ length: repeats }, () => arr).flat();
console.log(makeRepeated([1, 2, 3], 2));