给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
是否有理由不首先过滤数组以删除非数字?看起来很简单:
[1, 2, 3, null, 'a'].filter((x) => !isNaN(x)).reduce((a, b) => a + b)
其他回答
Vanilla JavaScript是您所需要的一切:
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(function(e){sum += e}); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(e => sum += e); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e in a) sum += e; sum
"00123foobar"
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e of a) sum += e; sum
10
var total = 0;
$.each(arr,function() {
total += this;
});
带reduce()
[1, 2, 3, 4].reduce((a, b) => a + b, 0); // 10
使用forEach()
let sum = 0;
[1, 2, 3, 4].forEach(n => sum += n);
sum; // 10
带参数
function arrSum(arr) {
sum = 0;
arr.forEach(n => sum += n);
return sum;
}
arrSum([1, 2, 3, 4]) // 10
了解底层流程的最简单答案:
let array = [10, 20, 30, 40, 50]
let total = 0
for(let i in array)
{
total += array[i]
}
console.log(total)
&如果您已经熟悉底层流程,那么内置方法可以节省您的时间:
let array = [10, 20, 30, 40, 50]
let total = array.reduce((x, y) => x + y)
console.log(total)
带ES6休息参数
让数组=[1,2,3,4]函数和(…数字){设总数=0;for(常量数){总数+=数量;}回报总额;}console.log(sum(…array));