如何找到数字数组的总和

JavaScript

樱Mandy

2020-03-11

给定一个数组[1, 2, 3, 4],如何找到其元素的总和?(在这种情况下,总和为10。)

我认为$.each可能有用,但是我不确定如何实现它。

第558篇《如何找到数字数组的总和》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

18个回答
番长神乐小小 2020.03.11

A simple method example:

function add(array){
    var arraylength = array.length;
    var sum = 0;
    for(var timesToMultiply = 0; timesToMultiply<arraylength; timesToMultiply++){
        sum += array[timesToMultiply];
    }

    return sum;
}

console.log(add([1, 2, 3, 4]));
伽罗小卤蛋米亚 2020.03.11

This is much easier

function sumArray(arr) {
    var total = 0;
    arr.forEach(function(element){
        total += element;
    })
    return total;
}

var sum = sumArray([1,2,3,4])

console.log(sum)
西里神乐 2020.03.11

Those are really great answers, but just in case if the numbers are in sequence like in the question ( 1,2,3,4) you can easily do that by applying the formula (n*(n+1))/2 where n is the last number

Gil村村 2020.03.11

No need to initial value! Because if no initial value is passed, the callback function is not invoked on the first element of the list, and the first element is instead passed as the initial value. Very cOOl feature :)

[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
村村凯宝儿 2020.03.11

You can combine reduce() method with lambda expression:

[1, 2, 3, 4].reduce((accumulator, currentValue) => accumulator + currentValue);
猴子村村 2020.03.11

Use a for loop:

const array = [1, 2, 3, 4];
let result = 0;

for (let i = 0; i < array.length - 1; i++) {
  result += array[i];
}

console.log(sum); // Should give 10

Or even a forEach loop:

const array = [1, 2, 3, 4];
let result = 0;

array.forEach(number => {
  result += number;
})

console.log(result); // Should give 10

For simplicity:

const array = [10, 20, 30, 40];
const add = (a, b) => a + b
const result = array.reduce(add);

console.log(result); // Should give 100
Stafan猴子 2020.03.11

Use reduce

let arr = [1, 2, 3, 4];

let sum = arr.reduce((v, i) => (v + i));

console.log(sum);

猴子NearJinJin 2020.03.11

A short piece of JavaScript code would do this job:

var numbers = [1,2,3,4];
var totalAmount = 0;

for (var x = 0; x < numbers.length; x++) {

    totalAmount += numbers[x];
}

console.log(totalAmount); //10 (1+2+3+4)
Near卡卡西 2020.03.11

A standard JavaScript solution:

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 */

This works for me (the result should be 5). I hope there is no hidden disadvantage in this kind of solution.

阳光伽罗 2020.03.11

Funny approach:

eval([1,2,3].join("+"))
乐十三 2020.03.11

Anyone looking for a functional oneliner like me? Take this:

sum= arr.reduce(function (a, b) {return a + b;}, 0);
神无梅 2020.03.11

You can also use reduceRight.

[1,2,3,4,5,6].reduceRight(function(a,b){return a+b;})

which results output as 21.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight

Itachi凯 2020.03.11
arr.reduce(function (a, b) {
    return a + b;
});

Reference: Array.prototype.reduce()

樱Itachi 2020.03.11
var arr = [1,2,3,4];
var total=0;
for(var i in arr) { total += arr[i]; }
古一古一 2020.03.11

为什么不减少?通常,这有点反直观,但使用它来查找总和非常简单:

var a = [1,2,3];
var sum = a.reduce(function(a, b) { return a + b; }, 0);
卡卡西Mandy 2020.03.11
var total = 0;
$.each(arr,function() {
    total += this;
});
JinJin猪猪 2020.03.11

Lisp中,这正是要完成的工作reduce您会看到以下代码:

(reduce #'+ '(1 2 3)) ; 6

幸运的是,在JavaScript中,我们还有reduce不幸的是,它+是一个运算符,而不是一个函数。但是我们可以使其漂亮!在这里,看看:

const sum = [1, 2, 3].reduce(add,0); // with initial value to avoid when the array is empty

function add(accumulator, a) {
    return accumulator + a;
}

console.log(sum); // 6

那不是很漂亮吗?:-)

更好!如果您使用的是ECMAScript 2015(又名ECMAScript 6),它可能会很漂亮:

const sum = [1, 2, 3].reduce((partial_sum, a) => partial_sum + a,0); 
console.log(sum); // 6
路易Green 2020.03.11

If you happen to be using Lodash you can use the sum function

array = [1, 2, 3, 4];
sum = _.sum(array); // sum == 10

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android