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)
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)
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)
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)
后者更兼容,正如您所看到的,两个解决方案都由两行代码表示.
归档时间: |
|
查看次数: |
59561 次 |
最近记录: |