给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
没有人提到函数式编程,但在这种情况下使用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));
其他回答
非常简单
步骤1我们应该有一个数组,如:
const arrayNumber = [500,152,154,1555,12445];
第2步(如果需要,可以忽略这个步骤)要确保表中的所有值都是数字
let newArray = [];
for (let i = 0; i < arrayNumber.length; i++) {
newArray.push(parseInt(arrayNumber[i], 10));
}
步骤3
const sumInArray = dataData.reduce( (a, b) => a + b);
最后
console.log(sumInArray);
//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))
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
使用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
此外,对于简单数组,使用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);