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
Fastest way to calculate the sum of array elements
提问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
回答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);