创建具有相同元素的数组重复的JavaScript多次 [英] Create an array with same element repeated multiple times in javascript
本文介绍了创建具有相同元素的数组重复的JavaScript多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python
[2] * 5
其中, [2]
是一个列表,给
[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;
};
感谢您。
推荐答案
您可以做到这一点是这样的:
You can do it like this:
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.
请注意:您还可以通过使用推改善你的函数很多
而不是 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;
}
这篇关于创建具有相同元素的数组重复的JavaScript多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文