Javascript | Set all values of an array

前端 未结 8 762
清酒与你
清酒与你 2020-12-29 19:45

Code

var cool = new Array(3);
cool[setAll] = 42; //cool[setAll] is just a pseudo selector..
alert(cool);

Result

相关标签:
8条回答
  • 2020-12-29 20:07

    Actually, you can use this perfect approach:

    let arr = Array.apply(null, Array(5)).map(() => 0);
    // [0, 0, 0, 0, 0]
    

    This code will create array and fill it with zeroes. Or just:

    let arr = new Array(5).fill(0)
    
    0 讨论(0)
  • 2020-12-29 20:13

    The other answers are Ok, but a while loop seems more appropriate:

    function setAll(array, value) {
      var i = array.length;
      while (i--) {
        array[i] = value;
      }
    }
    

    A more creative version:

    function replaceAll(array, value) {
      var re = new RegExp(value, 'g');
      return new Array(++array.length).toString().replace(/,/g, value).match(re);
    }
    

    May not work everywhere though. :-)

    0 讨论(0)
提交回复
热议问题