创建一个具有相同元素重复多次的数组 [英] 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 <来改善你的功能/ code>而不是
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屋!