创建一个重复多次相同元素的数组 [英] Create an array with same element repeated multiple times
问题描述
在 Python 中,[2]
是一个列表,下面的代码给出了这个输出:
In Python, where [2]
is a list, the following code gives this output:
[2] * 5 # Outputs: [2,2,2,2,2]
是否有一种简单的方法可以用 JavaScript 中的数组来做到这一点?
Does there exist an easy way to do this with an array in JavaScript?
我编写了以下函数来完成它,但有更短或更好的吗?
I wrote the following function to do it, but is there something shorter or better?
var repeatelem = function(elem, n){
// returns an array with element elem repeated n times.
var arr = [];
for (var i = 0; i <= n; i++) {
arr = arr.concat(elem);
};
return arr;
};
推荐答案
你可以这样做:
function fillArray(value, len) {
if (len == 0) return [];
var a = [value];
while (a.length * 2 <= len) a = a.concat(a);
if (a.length < len) a = a.concat(a.slice(0, len - a.length));
return a;
}
它在每次迭代中将数组翻倍,因此它可以创建一个非常大的数组,迭代次数很少.
It doubles the array in each iteration, so it can create a really large array with few iterations.
注意:您还可以通过使用 push
而不是 concat
来改进您的函数,因为 concat
将在每次迭代时创建一个新数组.像这样(仅作为如何使用数组的示例显示):
Note: You can also improve your function a lot by using push
instead of concat
, as concat
will create a new array each iteration. Like this (shown just as an example of how you can work with arrays):
function fillArray(value, len) {
var arr = [];
for (var i = 0; i < len; i++) {
arr.push(value);
}
return arr;
}
这篇关于创建一个重复多次相同元素的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!