Javascript 计算数组元素总和的最快方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8773303/
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 07:26:41  来源:igfitidea点击:

Fastest way to calculate the sum of array elements

javascript

提问by Pierre

I'm trying to find the fastest way to calculate the sum of elements contained in an array.
I managed to do it using eval(), but i consider eval as evil.

我试图找到计算数组中包含的元素总和的最快方法。
我设法使用eval(),但我认为eval 是邪恶的

var arr = [10,20,30,40,50];
console.log( eval( arr.join('+') ) ); //logs 150

Is there a better way to do it other than using a for loop?

除了使用 a 之外,有没有更好的方法来做到这一点for loop

I was thinking more about something like that, but it doesn't work:

我正在考虑更多类似的事情,但它不起作用:

var arr = [10,20,30,40,50];  

console.log( new Number( arr.join('+') ) ); //logs a Number Object  

console.log( new Number( arr.join('+') ).toString() ); //logs NaN

回答by Andreas

If supported you can use the reducemethod of Array

如果支持,您可以使用reduce方法Array

var arr = [10, 20, 30, 40, 50];

console.log(arr.reduce(function(prev, cur) {
    return prev + cur;
}));

回答by Ivan Castellanos

The best way is using a for loop. Is not the shortest, but is the best.

最好的方法是使用 for 循环。不是最短的,而是最好的。

回答by Sudhir Ojha

For loop is also better because arrays extend objects

For 循环也更好,因为数组扩展了对象

var arr = [10, 20, 30, 40, 50];
var sum = 0;
for(var i = 0; i < arr.length; i++){
   sum = sum + arr[i];
}
console.log("Sum of array = ",sum);