Javascript - Loop through sparse array and replace sparse values

后端 未结 3 1033
既然无缘
既然无缘 2021-01-21 04:54

I\'m trying to loop through a sparse array and fill in sparse elements with a value.

[\'foo\', \'bar\', , , ,].map(el => el || \'default\') // returns

3条回答
  •  长情又很酷
    2021-01-21 05:27

    This should do it:

    function Fill(n, _default) {
      return Array.apply(null,n).map(function(val) {
        return val || _default;
      });
    }
    var newa = Fill(myarray, "default");
    console.log(JSON.stringify(newa));
    

    Shown working here: https://jsfiddle.net/6vqsztxg/

提交回复
热议问题