简体   繁体   English

制作一个在数组中添加数字并在javascript中返回其总和的函数

[英]Making a function that adds numbers in an array and returns their sum in javascript

I'm trying to create a function that will add the numbers in an array and return their sum. 我正在尝试创建一个将数字加到数组中并返回其总和的函数。 For some reason it's returning 1 instead of 15 and I'm not sure why. 由于某种原因,它返回的是1而不是15,我不确定为什么。

var myArray = [1,2,3,4,5];  
function addThemUp(myArray) {
    var arrayTotal = myArray.length; 
    var totalSum = 0;

    for(var x = 0; x <arrayTotal; x++) {
        totalSum += myArray[x];
        return(totalSum)
    }
}

addThemUp(myArray)

You placed the return statement inside the loop, so it will sum the first element only and then return. 您将return语句放置在循环内,因此它将仅对第一个元素求和,然后返回。 Instead, you should allow the loop to complete, and return the sum only after its done: 相反,您应该允许循环完成,并且仅在完成后返回总和:

function addThemUp (myArray) {

    var arrayTotal = myArray.length; 
    var totalSum = 0;

    for(var x = 0; x < arrayTotal; x++){
        totalSum += myArray[x];
    }

    return(totalSum); // This is where the return should be
}

In your case, you need to fix where the return of totalSum is, to be the last statement of your function (after the loop). 对于您的情况,您需要确定totalSum返回的totalSum ,以作为函数的最后一条语句(在循环之后)。

That being said, you may find that adding up all the numbers in an array is much cleaner and simpler to do with reduce: 话虽这么说,您可能会发现将数组中的所有数字相加会比使用reduce更加简洁明了:

 function addThemUp(myArray) { return myArray.reduce(function(a, b) { return a + b; }); } var myArray = [1, 2, 3, 4, 5]; console.log(addThemUp(myArray)); 

You should return sum after for loop 您应该在for循环之后返回sum

var myArray = [1, 2, 3, 4, 5];

function addThemUp(myArray) {

    var arrayTotal = myArray.length;
    var totalSum = 0;

    for (var x = 0; x < arrayTotal; x++) {
        totalSum += myArray[x];
    }
    return totalSum;
}

console.log("Sum of all elements: " + addThemUp(myArray));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM