Most efficient way to create a zero filled JavaScr

2018-12-31 12:45发布

What is the most efficient way to create an arbitrary length zero filled array in JavaScript?

30条回答
还给你的自由
2楼-- · 2018-12-31 13:18

Elegant way to fill an array with precomputed values

Here is another way to do it using ES6 that nobody has mentioned so far:

> Array.from(Array(3), () => 0)
< [0, 0, 0]

It works by passing a map function as the second parameter of Array.from.

In the example above, the first parameter allocates an array of 3 positions filled with the value undefined and then the lambda function maps each one of them to the value 0.

Although Array(len).fill(0) is shorter, it doesn't work if you need to fill the array by doing some computation first (I know the question didn't ask for it, but a lot of people end up here looking for this).

For instance, if you need an array with 10 random numbers:

> Array.from(Array(10), () => Math.floor(10 * Math.random()))
< [3, 6, 8, 1, 9, 3, 0, 6, 7, 1]

It's more concise (and elegant) than the equivalent:

const numbers = Array(10);
for (let i = 0; i < numbers.length; i++) {
    numbers[i] = Math.round(10 * Math.random());
}

This method can also be used to generate sequences of numbers by taking advantage of the index parameter provided in the callback:

> Array.from(Array(10), (d, i) => i)
< [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Bonus answer: fill an array using String repeat()

Since this answer is getting a good deal of attention, I also wanted to show this cool trick. Although not as useful as my main answer, will introduce the still not very known, but very useful String repeat() method. Here's the trick:

> "?".repeat(10).split("").map(() => Math.floor(10 * Math.random()))
< [5, 6, 3, 5, 0, 8, 2, 7, 4, 1]

Cool, huh? repeat() is a very useful method to create a string that is the repetition of the original string a certain number of times. After that, split() creates an array for us, which is then map()ped to the values we want. Breaking it down in steps:

> "?".repeat(10)
< "??????????"

> "?".repeat(10).split("")
< ["?", "?", "?", "?", "?", "?", "?", "?", "?", "?"]

> "?".repeat(10).split("").map(() => Math.floor(10 * Math.random()))
< [5, 6, 3, 5, 0, 8, 2, 7, 4, 1]
查看更多
伤终究还是伤i
3楼-- · 2018-12-31 13:18
var str = "0000000...0000";
var arr = str.split("");

usage in expressions: arr[i]*1;

EDIT: if arr supposed to be used in integer expressions, then please don't mind the char value of '0'. You just use it as follows: a = a * arr[i] (assuming a has integer value).

查看更多
梦醉为红颜
4楼-- · 2018-12-31 13:19

It might be worth pointing out, that Array.prototype.fill had been added as part of the ECMAScript 6 (Harmony) proposal. I would rather go with the polyfill written below, before considering other options mentioned on the thread.

if (!Array.prototype.fill) {
  Array.prototype.fill = function(value) {

    // Steps 1-2.
    if (this == null) {
      throw new TypeError('this is null or not defined');
    }

    var O = Object(this);

    // Steps 3-5.
    var len = O.length >>> 0;

    // Steps 6-7.
    var start = arguments[1];
    var relativeStart = start >> 0;

    // Step 8.
    var k = relativeStart < 0 ?
      Math.max(len + relativeStart, 0) :
      Math.min(relativeStart, len);

    // Steps 9-10.
    var end = arguments[2];
    var relativeEnd = end === undefined ?
      len : end >> 0;

    // Step 11.
    var final = relativeEnd < 0 ?
      Math.max(len + relativeEnd, 0) :
      Math.min(relativeEnd, len);

    // Step 12.
    while (k < final) {
      O[k] = value;
      k++;
    }

    // Step 13.
    return O;
  };
}
查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 13:21

What about new Array(51).join('0').split('')?

查看更多
忆尘夕之涩
6楼-- · 2018-12-31 13:22

ES6 introduces Array.prototype.fill. It can be used like this:

new Array(len).fill(0);

Not sure if it's fast, but I like it because it's short and self-describing.

It's still not in IE (check compatibility), but there's a polyfill available.

查看更多
十年一品温如言
7楼-- · 2018-12-31 13:23

using object notation

var x = [];

zero filled? like...

var x = [0,0,0,0,0,0];

filled with 'undefined'...

var x = new Array(7);

obj notation with zeros

var x = [];
for (var i = 0; i < 10; i++) x[i] = 0;

As a side note, if you modify Array's prototype, both

var x = new Array();

and

var y = [];

will have those prototype modifications

At any rate, I wouldn't be overly concerned with the efficiency or speed of this operation, there are plenty of other things that you will likely be doing that are far more wasteful and expensive than instanciating an array of arbitrary length containing zeros.

查看更多
登录 后发表回答