如何将数组的每个成员乘以 javascript 中的标量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8454977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:04:33  来源:igfitidea点击:

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

javascriptarrays

提问by stephjang

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]

回答by BoltClock

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

Array.map()从 IE9 开始,IE 用户可以使用它,所以如果你根本不关心兼容性,你可以使用这个:

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

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

对于 JavaScript 1.8,这是尽可能短的:

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.

无论哪种方式,您都将遍历数组;Array.map()只是让你这样做不那么明显。

回答by Leon Adler

In ECMAScript 6, you can use arrow functions:

在 ECMAScript 6 中,您可以使用箭头函数

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

console.log(b);   // [5, 10, 15]


Arrow functions are syntactic sugarfor an inline function with lexical thisbinding:

箭头函数是具有词法绑定的内联函数的语法糖this

// 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 babeljsor TypeScriptin your project to cross-compile your code to ES5 syntax.

因此,如果您需要支持Internet Explorer 或其他旧浏览器(Edge 理解 ES6),您可以在您的项目中使用babeljsTypeScript将您的代码交叉编译为 ES5 语法。

回答by Bhesh Gurung

for(var i=0; i<a.length; i++) {
    a[i] *= 5;
}

回答by Gerald Senarclens de Grancy

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:

Ecmascript 2016 (ES7) 定义了 SIMD 数学,它允许像你想要的那样更快更容易地进行乘法运算。然而,截至今天,对 SIMD 的浏览器支持很少(只有 Firefox 每晚构建支持)[ 1]、[ 2]。这是它的样子:

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

在对 SIMD 的广泛支持之前,您必须求助于使用 map

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

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

所有现代浏览器都很好地支持它 [ 3]。

回答by Alvaro Gómez

You can use .map but you also have to create a new variable to throw the new values in:

您可以使用 .map 但您还必须创建一个新变量以将新值放入:

var a = [1,2,3];

var b = a.map(function(x){
    return x * 5;
});

alert(b);

回答by bennedich

var a, i, ii, term;

a = [1,2,3];
term = 5;

for (i=0, ii=a.length; i<ii; i++) {
  a[i] = a[i] * term;
}

回答by Abdul Munim

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);

回答by Mohammad Usman

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.

map()方法使用对调用数组中的每个元素调用提供的函数的结果创建一个新数组。

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

在我看来,.map()如果有人想根据当前数组的输入值创建一个新数组,则更合适。

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

但是,如果有人想就地修改数组,.forEach()似乎是更好的选择。

In ES6 we may use:

在 ES6 中,我们可以使用:

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

以下代码将修改给定的数组arr(不创建新数组):

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);

回答by scottlittle

Using Lodash's map function, this returns the original array a, multiplied by the constant 5:

使用 Lodash 的 map 函数,返回原始数组 a,乘以常数 5:

_.map( a, function multiply(x){ return x*5; } );