如何“重复"一个数组n次 [英] How to 'repeat' an array n times
本文介绍了如何“重复"一个数组n次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在python中,您可以执行以下操作:
In python you can do:
arr = [1,2,3] * 3
print(arr)
输出:
[1,2,3,1,2,3,1,2,3]
在Java脚本中是否有一种简洁的方法?我能想到的最好的是这样的:
Is there a concise way of doing this in java script? The best I can think of is something like:
let arr2 = [...arr, ...arr, ...arr]
但是如果我想做100次,那将是不切实际的.在python中,我会将其乘以100.
but if I wanted to do this 100 times it would be impractical. In python I would just multiply it by 100.
推荐答案
您可以执行以下操作:
var repeated = [].concat(... new Array(100).fill([1, 2, 3]));
这将创建一个给定长度的数组(此处为100),并用要重复的数组填充它([1, 2, 3]
).然后将该数组作为参数列表传播到[].concat()
.
That creates an array of a given length (100 here) and fills it with the array to be repeated ([1, 2, 3]
). That array is then spread as the argument list to [].concat()
.
哦,等一下
var repeated = new Array(100).fill([1, 2, 3]).flat();
会短一些.
这篇关于如何“重复"一个数组n次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文