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

后端 未结 9 1404
暖寄归人
暖寄归人 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);
    
    0 讨论(0)
  • 2021-02-06 23:38

    Array.map() is available to IE users as of IE9, so if you don't care about compatibility at all you can use this:

    var a = [1, 2, 3].map(function(x) { return x * 5; });
    

    For JavaScript 1.8, this is as short as you can go:

    var a = [1, 2, 3].map(function(x) x * 5);
    

    If you need maximal browser compatibility, you'll have to put up with a loop.

    Either way you'll be iterating over the array; Array.map() just makes it less obvious you're doing so.

    0 讨论(0)
  • 2021-02-06 23:54

    In ECMAScript 6, you can use arrow functions:

    var a = [1, 2, 3];
    var b = a.map(x => x * 5); // <-------
    
    console.log(b);   // [5, 10, 15]
    

    Arrow functions are syntactic sugar for an inline function with lexical this binding:

    // ES6
    let array2 = array1.map(x => x * 5);
    
    // ES5
    var array2 = array1.map((function (x) { return x * 5; }).bind(this));
    

    Therefore, if you need to support Internet Explorer or other old browsers (Edge understands ES6) you can use babeljs or TypeScript in your project to cross-compile your code to ES5 syntax.

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