给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
Object.defineProperty(Object.prototype, 'sum', {
enumerable:false,
value:function() {
var t=0;for(var i in this)
if (!isNaN(this[i]))
t+=this[i];
return t;
}
});
[20,25,27.1].sum() // 72.1
[10,"forty-two",23].sum() // 33
[Math.PI,0,-1,1].sum() // 3.141592653589793
[Math.PI,Math.E,-1000000000].sum() // -999999994.1401255
o = {a:1,b:31,c:"roffelz",someOtherProperty:21.52}
console.log(o.sum()); // 53.519999999999996
其他回答
arr.reduce(function (a, b) {
return a + b;
});
参考:Array.prototype.reduce()
带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
此外,对于简单数组,使用es6求和。
const sum = [1, 2, 3].reduce((partial_sum, a) => partial_sum + a,0);
console.log(sum);
对于具有默认初始化值的对象数组
const totalAmount = obj =>
Object.values(obj).reduce((acc, { order_qty, mrp_price }) =>
acc + order_qty * mrp_price, 0);
console.log(totalAmount);
//Try this way
const arr = [10,10,20,60];
const sumOfArr = (a) =>{
let sum=0;
for(let i in a) {
sum += a[i];
}
return sum;
}
console.log(sumOfArr(arr))
也可以使用reduceRight。
[1,2,3,4,5,6].reduceRight(function(a,b){return a+b;})
其结果输出为21。
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight