Javascript sum of highest 6 values in an array(数组中最高 6 个值的 Javascript 总和)
问题描述
我有一个大约 10 个值的数组,我想知道 JS 或 JQuery 是否有任何方法可以将最高的 6 个值相加并得到总数.
I have an array of roughly 10 values, and I was wondering if there was any way with JS or JQuery to add up the highest 6 values and get a total.
推荐答案
这里:
var top6Total = arr
.map(function (v) { return +v; })
.sort(function (a,b) { return a-b; })
.slice( -6 )
.reduce(function (a,b) { return a+b; });
现场演示: http://jsfiddle.net/bPwYB/
(注意:您必须 polyfill .reduce()
对于 IE8.)
(Note: You would have to polyfill .reduce()
for IE8.)
这篇关于数组中最高 6 个值的 Javascript 总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!