How do I multiply each member of an array by a scalar in javascript?

后端 未结 9 1391
暖寄归人
暖寄归人 2021-02-06 22:55

For example, how do I achieve the following without iterating over the array?

var a = [1, 2, 3] * 5;  // a should equal [5, 10, 15]
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 23:32

    You can try this:

    function scalarMultiply(arr, multiplier) {
       for (var i = 0; i < arr.length; i++)
       {
          arr[i] *= multiplier;
       }
       return arr;
    }
    

    USAGE

    var a = scalarMultiply([1, 2, 3], 5);
    

提交回复
热议问题