给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
getTotal = (arr) => {
let total = 0
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total
}
getTotal([1, 2, 3, 4]) // 10
getTotal([1, 2, 3, 4, 5]) // 15
其他回答
使用递归
var sum = (arr) => arr.length === 1 ? arr[0] : arr.shift() + sum(arr);
sum([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);
这里有一个优雅的单线解决方案,它使用堆栈算法,尽管人们可能需要一些时间来理解这个实现的美。
const getSum = arr => (arr.length === 1) ? arr[0] : arr.pop() + getSum(arr);
getSum([1, 2, 3, 4, 5]) //15
基本上,该函数接受一个数组,并检查该数组是否正好包含一个项。如果为false,则从堆栈中弹出最后一项并返回更新的数组。
这段代码的妙处在于,该函数包括arr[0]检查,以防止无限循环。一旦到达最后一项,它将返回全部金额。
一些人建议在Array.prototype中添加.sum()方法。这通常被认为是不好的做法,所以我不建议您这样做。
如果你仍然坚持这样做,那么这是一种简洁的写作方式:
Array.prototype.sum = function() {return [].reduce.call(this, (a,i) => a+i, 0);}
然后:[1,2].sum();//3.
注意,添加到原型中的函数使用了ES5和ES6函数以及箭头语法的混合。声明该函数是为了允许该方法从正在操作的Array中获取this上下文。为了简洁起见,我在reduce调用中使用了=>。
使用for循环:
const array = [1, 2, 3, 4];
let result = 0;
for (let i = 0; i < array.length - 1; i++) {
result += array[i];
}
console.log(result); // Should give 10
甚至是forEach循环:
const array = [1, 2, 3, 4];
let result = 0;
array.forEach(number => {
result += number;
})
console.log(result); // Should give 10
为简单起见,请使用reduce:
const array = [10, 20, 30, 40];
const add = (a, b) => a + b
const result = array.reduce(add);
console.log(result); // Should give 100