默认数组值

Der*_*air 30 javascript arrays

有没有办法在javascript中为数组分配默认值?

例如: an array with 24 slots that defaults to 0

dea*_*unk 51

var a = Array.apply(null, Array(24)).map(function() { return 0 });

// or:
var a = Array.apply(null, Array(5)).map(Boolean).map(Number);
Run Code Online (Sandbox Code Playgroud)

  • +1不会更改Array原型. (12认同)
  • 如何在第一个阵列上允许地图?关于构造数组的方式允许地图工作,而通常不会 (2认同)

Aik*_*Aik 31

您可以fill在数组上使用该函数:

Array(24).fill(0)
Run Code Online (Sandbox Code Playgroud)

注意: fill仅在ECMAScript 2015(别名"6")中引入,因此截至2017年,浏览器支持仍然非常有限(例如没有Internet Explorer).


ken*_*bec 23

Array.prototype.repeat= function(what, L){
 while(L) this[--L]= what;
 return this;
}
Run Code Online (Sandbox Code Playgroud)

var A = [] .repeat(0,24);

警报(A)

  • 这已经很晚了,但我只想添加到将来阅读本文的人:**不要称之为'repeat`**,因为ES6 _will_实现了`repeat`方法,这意味着你将覆盖默认行为,这是不鼓励的.不错的解决方案. (3认同)
  • 什么是奇怪的(Javascript明智的)命名约定?(@使用大写字母.) (2认同)

tva*_*son 22

有点罗嗦,但它确实有效.

var aray = [ 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0 ];
Run Code Online (Sandbox Code Playgroud)

  • @KnickerKicker - 不,对于一次性的24元素数组,我可能会这样做.如果它是大量的物品或我反复需要它,那么我会更加聪明. (3认同)
  • 实际上,这并没有回答"有没有办法在javascript中为数组分配默认值?" 这个答案所解决的是澄清的例子. (3认同)
  • 到目前为止,创建一个包含24个零的数组的最有效和最干净的方法. (3认同)

Saj*_*eri 15

最好和最简单的解决方案是:

Array(length of the array).fill(a default value you want to put in the array)
Run Code Online (Sandbox Code Playgroud)

例子

Array(5).fill(1)
Run Code Online (Sandbox Code Playgroud)

结果将是

[1,1,1,1,1]
Run Code Online (Sandbox Code Playgroud)

你可以放任何你喜欢的东西:

Array(5).fill({name : ""})
Run Code Online (Sandbox Code Playgroud)

现在,如果您想更改数组中的某些当前值,您可以使用

[the created array ].fill(a new value , start position, end position(not included) )
Run Code Online (Sandbox Code Playgroud)

喜欢

[1,1,1,1,1].fill("a",1,3)
Run Code Online (Sandbox Code Playgroud)

和输出是

[1, "a", "a", 1, 1]
Run Code Online (Sandbox Code Playgroud)


Vit*_*ile 11

如果您使用"非常现代"的浏览器(查看兼容性表),您可以依赖fill:

var array = new Array(LENGTH);
array.fill(DEFAULT_VALUE);
Run Code Online (Sandbox Code Playgroud)

由于几个原因,new Array()很多开发人员都不赞赏使用它; 所以你可以这样做:

var array = [];
for(var i=0; i<LENGTH; ++i) array.push(DEFAULT_VALUE);
Run Code Online (Sandbox Code Playgroud)

后者更兼容,正如您所看到的,两个解决方案都由两行代码表示.