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:01

The already mentioned ES 6 fill method takes care of this nicely. Most modern desktop browsers already support the required Array prototype methods as of today (Chromium, FF, Edge and Safari) [1]. You can look up details on MDN. A simple usage example is

a = new Array(10).fill(0);

Given the current browser support you should be cautious to use this unless you are sure your audience uses modern Desktop browsers.

查看更多
后来的你喜欢了谁
3楼-- · 2018-12-31 13:02

I have nothing against:

Array.apply(null, Array(5)).map(Number.prototype.valueOf,0);
new Array(5+1).join('0').split('').map(parseFloat);

suggested by Zertosh, but in a new ES6 array extensions allow you to do this natively with fill method. Now IE edge, Chrome and FF supports it, but check the compatibility table

new Array(3).fill(0) will give you [0, 0, 0]. You can fill the array with any value like new Array(5).fill('abc') (even objects and other arrays).

On top of that you can modify previous arrays with fill:

arr = [1, 2, 3, 4, 5, 6]
arr.fill(9, 3, 5)  # what to fill, start, end

which gives you: [1, 2, 3, 9, 9, 6]

查看更多
只靠听说
4楼-- · 2018-12-31 13:03
function makeArrayOf(value, length) {
  var arr = [], i = length;
  while (i--) {
    arr[i] = value;
  }
  return arr;
}

makeArrayOf(0, 5); // [0, 0, 0, 0, 0]

makeArrayOf('x', 3); // ['x', 'x', 'x']

Note that while is usually more efficient than for-in, forEach, etc.

查看更多
临风纵饮
5楼-- · 2018-12-31 13:04

Although this is an old thread, I wanted to add my 2 cents to it. Not sure how slow/fast this is, but it's a quick one liner. Here is what I do:

If I want to pre-fill with a number:

Array.apply(null, Array(5)).map(Number.prototype.valueOf,0);
// [0, 0, 0, 0, 0]

If I want to pre-fill with a string:

Array.apply(null, Array(3)).map(String.prototype.valueOf,"hi")
// ["hi", "hi", "hi"]

Other answers have suggested:

new Array(5+1).join('0').split('')
// ["0", "0", "0", "0", "0"]

but if you want 0 (the number) and not "0" (zero inside a string), you can do:

new Array(5+1).join('0').split('').map(parseFloat)
// [0, 0, 0, 0, 0]
查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 13:04

Using lodash or underscore

_.range(0, length - 1, 0);

Or if you have an array existing and you want an array of the same length

array.map(_.constant(0));
查看更多
明月照影归
7楼-- · 2018-12-31 13:04

The fastest way to do that is with forEach =)

(we keep backward compatibility for IE < 9)

var fillArray = Array.prototype.forEach
    ? function(arr, n) {
         arr.forEach(function(_, index) { arr[index] = n; });
         return arr;
      }
    : function(arr, n) {
         var len = arr.length;
         arr.length = 0;
         while(len--) arr.push(n);
         return arr;
      };

// test
fillArray([1,2,3], 'X'); // => ['X', 'X', 'X']
查看更多
登录 后发表回答