给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
无需初始值!因为如果没有传递初始值,则不会对列表的第一个元素调用回调函数,而是将第一个元素作为初始值传递。非常酷的功能:)
[1, 2, 3, 4].reduce((a, x) => a + x) // 10
[1, 2, 3, 4].reduce((a, x) => a * x) // 24
[1, 2, 3, 4].reduce((a, x) => Math.max(a, x)) // 4
[1, 2, 3, 4].reduce((a, x) => Math.min(a, x)) // 1
其他回答
var totally = eval(arr.join('+'))
这样你就可以在阵列中放置各种各样的异国情调的东西。
var arr = ['(1/3)','Date.now()','foo','bar()',1,2,3,4]
我只是半开玩笑。
标准JavaScript解决方案:
var addition = [];
addition.push(2);
addition.push(3);
var total = 0;
for (var i = 0; i < addition.length; i++)
{
total += addition[i];
}
alert(total); // Just to output an example
/* console.log(total); // Just to output an example with Firebug */
这对我有用(结果应该是5)。我希望这种解决方案没有隐藏的缺点。
一小段JavaScript代码就能完成这项工作:
var numbers = [1,2,3,4];
var totalAmount = 0;
for (var x = 0; x < numbers.length; x++) {
totalAmount += numbers[x];
}
console.log(totalAmount); //10 (1+2+3+4)
var total = 0;
$.each(arr,function() {
total += this;
});
这正是减薪的工作。
如果您使用的是ECMAScript 2015(又名ECMAScript6):
constsum=[1,2,3]。reduce((partialSum,a)=>partialSum+a,0);console.log(总和);//6.
对于旧的JS:
常量sum=[1,2,3]。reduce(add,0);//数组为空时避免使用初始值函数add(累加器,a){返回蓄能器+a;}console.log(总和);//6.
这不是很漂亮吗?:-)