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

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

    Ecmascript 2016 (ES7) defines SIMD mathematics which allow to do multiplications like the one you desire faster and easier. However, as of today there is very little browser support for SIMD (only Firefox nightly builds support this) [1], [2]. This is how it will look like:

    var a = SIMD.Float32x4(1, 2, 3);
    var b = SIMD.Float32x4(5, 5, 5);
    SIMD.Float32x4.mul(a, b);  // Float32x4[5, 10, 15]
    

    Until there will be widespread support for SIMD you'd have to resort to using map

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

    which is nicely supported by all modern browsers [3].

提交回复
热议问题