给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[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)
其他回答
无需初始值!因为如果没有传递初始值,则不会对列表的第一个元素调用回调函数,而是将第一个元素作为初始值传递。非常酷的功能:)
[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
有人在找像我这样的功能性的oneliner吗?
假设:
const arr = [1, 2, 3, 4];
这是现代JS的一条直线:
sum = arr.reduce((a, b) => a + b, 0);
(如果您碰巧需要支持没有箭头功能的旧IE:)
sum = arr.reduce(function (a, b) {return a + b;}, 0);
注意,这里的初始值是0,因此如果需要,可以将其用作偏移量。还要注意,需要这个初始值,否则使用空数组调用函数将出错。
你可以试试这个:
var arr = [100,114,250,1200];
var total = 0;
for(var i in arr){
total += parseInt(arr[i]);
}
console.log(total);
输出将为:1664
或者,如果值为Float,请尝试以下操作:
var arr = [100.00,114.50,250.75,1200.00];
var total = 0;
for(var i in arr){
total += parseFloat(arr[i]);
}
console.log(total.toFixed(2));
输出将为:1665.25
此外,对于简单数组,使用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);
没有人提到函数式编程,但在这种情况下使用Ramda是非常干净的方法:
//Assuming you use nodejs, but can also be used in browser
const R = require('ramda');
let nums = [2, 4, 6, 8, 10];
console.log(R.sum(nums));