我如何在javascript中的标量乘以一个阵列中的每个成员? [英] How do I multiply each member of an array by a scalar in javascript?
问题描述
例如,我该如何实现下面的不反复阵列上
VAR一个= [1,2,3] * 5; //一个应等于[5,10,15]
<一个href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map\"><$c$c>Array.map()$c$c>提供给用户的IE浏览器IE9作为的,所以如果你根本不关心的兼容性,可以使用这样的:
VAR一个= [1,2,3] .MAP(函数(X){返回X * 5;});
对于JavaScript 1.8,这是短,你可以去:
VAR一个= [1,2,3] .MAP(函数(x)x * 5);
如果您需要最大的浏览器兼容性,你必须忍受一个循环。
无论哪种方式,你会遍历数组结束; Array.map()
只是使它不那么明显你这样做。
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]
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.
这篇关于我如何在javascript中的标量乘以一个阵列中的每个成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!