Most efficient way to create a zero filled JavaScript array?

前端 未结 30 1736
花落未央
花落未央 2020-11-22 05:58

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

30条回答
  •  眼角桃花
    2020-11-22 06:16

    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.

提交回复
热议问题