Javascript 创建一个重复多次相同元素的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12503146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:33:06  来源:igfitidea点击:

Create an array with same element repeated multiple times

javascriptarraysrepeat

提问by Curious2learn

In Python, where [2]is a list, the following code gives this output:

在 Python 中, where[2]是一个列表,下面的代码给出了这个输出:

[2] * 5 # Outputs: [2,2,2,2,2]

Does there exist an easy way to do this with an array in JavaScript?

是否有一种简单的方法可以用 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;
};

采纳答案by Guffa

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.

它在每次迭代中将数组加倍,因此它可以通过很少的迭代创建一个非常大的数组。



Note: You can also improve your function a lot by using pushinstead of concat, as concatwill create a new array each iteration. Like this (shown just as an example of how you can work with arrays):

注意:您还可以通过使用push代替 来改进您的函数concat,因为concat每次迭代都会创建一个新数组。像这样(仅作为如何使用数组的示例显示):

function fillArray(value, len) {
  var arr = [];
  for (var i = 0; i < len; i++) {
    arr.push(value);
  }
  return arr;
}

回答by Niko Ruotsalainen

In ES6 using Array fill()method

在 ES6 中使用 Array fill()方法

Array(5).fill(2)
//=> [2, 2, 2, 2, 2]

回答by Janus Troelsen

>>> Array.apply(null, Array(10)).map(function(){return 5})
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
>>> //Or in ES6
>>> [...Array(10)].map((_, i) => 5)
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]

回答by Vivek

you can try:

你可以试试:

Array(6).join('a').split(''); // returns ['a','a','a','a','a'] (5 times)

Update (01/06/2018):

更新(01/06/2018)

Now you can have a set of characters repeating.

现在你可以有一组重复的字符。

new Array(5).fill('a'); // give the same result as above;
// or
Array.from({ length: 5 }).fill('a')

Note: Check more about fill(...)and from(...)for compatibility and browser support.

注意:查看更多关于fill(...)from(...)的兼容性和浏览器支持。

Update (05/11/2019):

更新(05/11/2019)

Another way, without using fillor from, that works for string of any length:

另一种不使用fillor 的方法from适用于任何长度的字符串:

Array.apply(null, Array(3)).map(_ => 'abc') // ['abc', 'abc', 'abc']

Same as above answer. Adding for sake of completeness.

与上述答案相同。为了完整性而添加。

回答by Thomson

Array.from({length:5}, i => 1) // [1, 1, 1, 1, 1]

Array.from({length:5}, i => 1) // [1, 1, 1, 1, 1]

or create array with increasing value

或创建具有递增值的数组

Array.from({length:5}, (e, i)=>i) // [0, 1, 2, 3, 4]

Array.from({length:5}, (e, i)=>i) // [0, 1, 2, 3, 4]

回答by Droogans

In lodashit's not so bad:

lodash 中它并没有那么糟糕:

_.flatten(_.times(5, function () { return [2]; }));
// [2, 2, 2, 2, 2]

EDIT: Even better:

编辑:甚至更好:

_.times(5, _.constant(2));
// [2, 2, 2, 2, 2]

EDIT: Even better:

编辑:甚至更好:

_.fill(Array(5), 2);

回答by brook hong

[c] * ncan be written as:

[c] * n可以写成:

Array(n+1).join(1).split('').map(function(){return c;})

so for [2] * 5

因此对于 [2] * 5

Array(6).join(1).split('').map(function(){return 2;})

回答by Shmiddty

You can also extend the functionality of Array like so:

您还可以像这样扩展 Array 的功能:

Array.prototype.fill = function(val){
    for (var i = 0; i < this.length; i++){
        this[i] = val;
    }
    return this;
};
// used like:
var arry = new Array(5)?.fill(2);
// or
var arry = new Array(5);
arry.fill(2);


?console.log(arry);? //[2, 2, 2, 2, 2] 

I should note that extending the functionality of built-in objects can cause problems if you are working with 3rd-party libraries. Always weigh this into your decisions.

我应该注意,如果您正在使用 3rd-party 库,扩展内置对象的功能可能会导致问题。始终在您的决定中权衡这一点。

回答by Henrik Christensen

In case you need to repeat an arrayseveral times:

如果您需要多次重复数组

var arrayA = ['a','b','c'];
var repeats = 3;
var arrayB = Array.apply(null, {length: repeats * arrayA.length})
        .map(function(e,i){return arrayA[i % arrayA.length]});
// result: arrayB = ['a','b','c','a','b','c','a','b','c']

inspired by this answer

受到这个答案的启发

回答by noobninja

In the Node.js REPL:

在 Node.js REPL 中:

> Array.from({length:5}).map(x => 2)
[ 2, 2, 2, 2, 2 ]