Javascript 幾種 Array 填充 0 的方式

# Array push
for (var i = 0, a = []; i < 100; i++) a.push(0);

# Array assign
for (var i = 0, a = new Array(100); i < 100;) a[i++] = 0;

# Typed array conversion (最慢)
[].slice.call(new Uint8Array(100));

# Binary concatenation
for (var i = 100, a = [], add = [0]; i; i >>=1) {
    if (i & 1) a.push.apply(a, add);
    add.push.apply(add, add);
}

# Array Apply
Array.apply(null, new Array(100)).map(Number.prototype.valueOf,0);

# Array.fill() (最快)
new Array(100).fill(0);

Most efficient way to create a zero filled JavaScript array? – Stack
Overflow Zero filled array creation

Leave a Reply

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>