给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
也可以使用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
其他回答
标准JavaScript解决方案:
var addition = [];
addition.push(2);
addition.push(3);
var total = 0;
for (var i = 0; i < addition.length; i++)
{
total += addition[i];
}
alert(total); // Just to output an example
/* console.log(total); // Just to output an example with Firebug */
这对我有用(结果应该是5)。我希望这种解决方案没有隐藏的缺点。
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
没有人提到函数式编程,但在这种情况下使用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));
这可以通过循环所有项,并在每次迭代中将它们添加到一个和变量中来实现。
var array = [1, 2, 3];
for (var i = 0, sum = 0; i < array.length; sum += array[i++]);
JavaScript不知道块的作用域,所以可以访问sum:
console.log(sum); // => 6
同上,但注释和准备为简单函数:
function sumArray(array) {
for (
var
index = 0, // The iterator
length = array.length, // Cache the array length
sum = 0; // The total amount
index < length; // The "for"-loop condition
sum += array[index++] // Add number on each iteration
);
return sum;
}
了解底层流程的最简单答案:
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)