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

后端 未结 9 1325
暖寄归人
暖寄归人 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:31

    As stated in Docs:

    The map() method creates a new array with the results of calling a provided function on every element in the calling array.

    In my opinion, .map() is more suitable if someone wants to create a new array based on input values from the current array.

    However, if someone wants to modify the array in place, .forEach() seems a better choice.

    In ES6 we may use:

    • Array.prototype.forEach()
    • Arrow functions

    Following code will modify a given array arr in place (without creating a new one):

    arr.forEach((value, index) => {arr[index] *= 5});
    

    Demo:

    var arr = [1, 2, 3];
    var scalar = 5;
    
    arr.forEach((value, index) => {
        arr[index] *= scalar;
    });
    console.log(arr);

提交回复
热议问题