Rah*_*thi 20
怎么样这样:
Array.apply(null, new Array(10)).map(Number.prototype.valueOf,0);
//Output as [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)
要么
new Array(10+1).join('0').split('').map(parseFloat)
//Output as [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)
编辑:-
如果你的数组是动态的,那么只需将它放在一个带有数字的函数中,并用该变量替换10.
dea*_*unk 17
默认情况下Uint8Array,Uint16Array和Uint32Array阶级保持为零,因为它的价值,所以你不需要任何复杂的充填技术,只是:
var ary = new Uint8Array(10);
Run Code Online (Sandbox Code Playgroud)
ary默认情况下,数组的所有元素都将为零.
Sal*_*ali 13
新的ES6阵列扩展允许您使用fill方法本机执行此操作.现在IE边缘,Chrome和FF支持它,但检查兼容性表
new Array(3).fill(0)会给你的[0, 0, 0].您可以使用任何值填充数组new Array(5).fill('abc')(甚至是对象和其他数组).
最重要的是,您可以使用fill修改以前的数组:
arr = [1, 2, 3, 4, 5, 6]
arr.fill(9, 3, 5) # what to fill, start, end
Run Code Online (Sandbox Code Playgroud)
这给你: [1, 2, 3, 9, 9, 6]
在Javascript ES6中,有一个非常简单的解决方案。我来这里是因为我想对它进行简短编码:
n = 999 // arbitrary length
a = Array(n).fill(0)
console.log(a)Run Code Online (Sandbox Code Playgroud)
如果你想要一个9长度的数组:
Array.apply(null, {length: 9}).map(function() {return 0;})
Run Code Online (Sandbox Code Playgroud)
如果你想要一个X长度数组:
Array.apply(null, {length: X}).map(function() {return 0;})
Run Code Online (Sandbox Code Playgroud)
如果您有一个数组并想要重写其值:
var arr=[54,53,6,7,88,76]
arr=arr.map(function() {return 0;})
Run Code Online (Sandbox Code Playgroud)
你可以用你想要的任何东西填充数组,只需在.map中的函数内部返回值改变:
Array.apply(null, {length: 9}).map(function() {return "a string";})
Array.apply(null, {length: 9}).map(function() {return Math.random();})
Array.apply(null, {length: 9}).map(function() {return NaN;})
Array.apply(null, {length: 9}).map(function() {return null;})
Array.apply(null, {length: 9}).map(function() {return true;})
Array.apply(null, {length: 9}).map(function() {return;})
Run Code Online (Sandbox Code Playgroud)
最后一个将使用undefined填充数组
function repeatArray(value, len){
var A=[],i=0;
while (i<len) A[i++]= value;
return A;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24050 次 |
| 最近记录: |