最快的 JavaScript 求和 [英] Fastest JavaScript summation
本文介绍了最快的 JavaScript 求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 JavaScript 中总结数组的最快方法是什么?快速搜索翻了几种不同的方法,但如果可能的话,我想要一个本地解决方案.这将在 SpiderMonkey 下运行.
What is the fastest way to sum up an array in JavaScript? A quick search turns over a few different methods, but I would like a native solution if possible. This will run under SpiderMonkey.
我一直在使用的非常内在的思考:
Thinking very inside-the-box I have been using:
var count = 0;
for(var i = 0; i < array.length; i++)
{
count = count + array[i];
}
我确信有比直接迭代更好的方法.
I'm sure there is a better way then straight iteration.
推荐答案
你应该能够使用 reduce
.
var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0);
并且随着 箭头函数引入ES6,更简单:
And with arrow functions introduced in ES6, it's even simpler:
sum = array.reduce((pv, cv) => pv + cv, 0);
这篇关于最快的 JavaScript 求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文