Javascript 用单个值初始化数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4049847/
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 07:15:51  来源:igfitidea点击:

Initializing an Array with a Single Value

javascript

提问by oldestlivingboy

Is there a more compact way to do this sort of initialization?

有没有更紧凑的方法来进行这种初始化?

for (var i = 0; i < arraySize; i++) array[i] = value;

采纳答案by DoXicK

while(arraySize--) array.push(value);

no initialization (that i know of)

没有初始化(我知道)



Update

更新

Since ever posting this answer 4 years ago, people seem to keep coming back here for this answer. For benchmarking purposes I made a JSPerfwith some different solutions.

自从 4 年前发布这个答案以来,人们似乎不断回到这里寻找这个答案。出于基准测试的目的,我用一些不同的解决方案制作了一个JSPerf

The solution above here isn't the quickest, although it's short. To stick to the same short style, but with a better performance:

上面的解决方案不是最快的,尽管它很短。坚持同样的短风格,但具有更好的性能:

while(size--) array[size] = value;


Update Feb 2016Updated the JSPerf with a new revision with more testcases.

2016 年 2 月更新更新了 JSPerf 的新修订版和更多测试用例。

If performance doesn't matter and you want a one-liner:

如果性能无关紧要并且您想要单线:

var value = 1234, // can be replaced by a fixed value
    size  = 1000, // can be replaced by a fixed value
    array = Array.apply(null,{length: size}).map(function() { return value; });

A more performant solution (in one, dirty, line): Be aware: this replaces existsing value, size and i variables in the scope

一个更高效的解决方案(在一个,脏,行): 注意:这会替换作用域中的现有值、大小和 i 变量

for(var i = 0, value = 1234, size = 1000, array = new Array(1000); i < size; i++) array[i] = value;

回答by Klaus Byskov Pedersen

One short way of doing it would be:

一种简短的方法是:

var arr = Array(arraySize).fill(value);

Would make arr = Array [ 0, 0, 0, 0, 0 ]if arraySize == 5and value == 0, for example.

会使arr = Array [ 0, 0, 0, 0, 0 ]ifarraySize == 5value == 0,例如。

回答by magikMaker

I think this is nice, short and elegant:

我认为这很好,简短而优雅:

// assuming `value` is what you want to fill the array with
// and `arraySize` is the size of the array
Array(arraySize).fill(value);

回答by Aequitas

The OP seems to be after compactness in a single-use scenario over efficiency and re-usability. For others looking for efficiency, here's an optimization that hasn't been mentioned yet. Since you know the length of the array in advance, go ahead and set it before assigning the values. Otherwise, the array's going to be repeatedly resized on the fly -- not ideal!

OP 似乎在一次性使用场景中追求效率和可重用性的紧凑性。对于其他寻求效率的人,这里有一个尚未提及的优化。由于您事先知道数组的长度,因此请在分配值之前对其进行设置。否则,数组将在运行中反复调整大小 - 不理想!

function initArray(length, value) {
    var arr = [], i = 0;
    arr.length = length;
    while (i < length) { arr[i++] = value; }
    return arr;
}

var data = initArray(1000000, false);

回答by Christopher Weiss

This is not as compact but is arguably more direct.

这不是那么紧凑,但可以说更直接。

array = Array.apply(null, new Array(arraySize)).map(function () {return value;});

回答by Christopher Weiss

This is not likely to be better than any of the techniques above but it's fun...

这不太可能比上述任何一种技术更好,但它很有趣......

var a = new Array(10).join('0').split('').map(function(e) {return parseInt(e, 10);})

回答by Kyaw Tun

For efficiency, I would avoid push. So simply

为了效率,我会避免push. 就这么简单

for (var i = 0; i < arraySize; i++) array[i] = value; 

For IE10:

对于 IE10:

array = new Array(arraySize); 
for (var i = 0; i < arraySize; i++) array[i] = value; 

Edit: modified as discussed in the comments.

编辑:按照评论中的讨论进行修改。

回答by álvaro González

If you need to do it many times, you can always write a function:

如果你需要做很多次,你总是可以写一个函数:

function makeArray(howMany, value){
    var output = [];
    while(howMany--){
        output.push(value);
    }
    return output;
}

var data = makeArray(40, "Foo");

And, just for completeness (fiddling with the prototype of built-in objects is often not a good idea):

而且,只是为了完整性(摆弄内置对象的原型通常不是一个好主意):

Array.prototype.fill = function(howMany, value){
    while(howMany--){
        this.push(value);
    }
}

So you can now:

所以你现在可以:

var data = [];
data.fill(40, "Foo");


Update: I've just seen your note about arraySizebeing a constant or literal. If so, just replace all while(howMany--)with good old for(var i=0; i<howMany; i++).

更新:我刚刚看到您关于arraySize成为常量或文字的注释。如果是这样,只需将所有内容替换while(howMany--)为 good old for(var i=0; i<howMany; i++)

回答by Rick Love

This is an old question, but I use this in modern JS:

这是一个老问题,但我在现代 JS 中使用它:

[...new Array(1000000)].map(()=>42);

回答by Joshua Robinson

Stumbled across this one while exploring array methods on a plane.. ohhh the places we go when we are bored. :)

在飞机上探索数组方法时偶然发现了这个……哦,我们无聊时去的地方。:)

var initializedArray = new Array(30).join(null).split(null).map(function(item, index){
  return index;
});

.map()and nullfor the win! I like null because passing in a string like up top with '0' or any other value is confusing. I think this is more explicit that we are doing something different.

.map()null为赢!我喜欢 null 因为传递像 up top 这样的带有 '0' 或任何其他值的字符串是令人困惑的。我认为这更明确地表明我们正在做一些不同的事情。

Note that .map()skips non-initialized values. This is why new Array(30).map(function(item, index){return index});does not work. The new .fill()method is preferred if available, however browser support should be noted as of 8/23/2015.

请注意,.map()跳过未初始化的值。这就是为什么new Array(30).map(function(item, index){return index});不起作用。新的.fill()优选方法如果有的话,但是浏览器支持应当注意作为2015年8月23日

Desktop (Basic support)

桌面(基本支持)

  • Chrome 45 (36 1)
  • Firefox (Gecko) 31 (31)
  • Internet Explorer Not supported
  • Opera Not supported
  • Safari 7.1
  • 铬 45 (36 1)
  • 火狐(壁虎) 31 (31)
  • 不支持 Internet Explorer
  • 歌剧 不支持
  • Safari 7.1

From MDN:

来自MDN

[1, 2, 3].fill(4);               // [4, 4, 4]
[1, 2, 3].fill(4, 1);            // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2);         // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1);         // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2);       // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN);     // [1, 2, 3]
Array(3).fill(4);                // [4, 4, 4]
[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}