简体   繁体   中英

JavaScript Loop stuck beginner

I am trying some loops and in this specific I do not understand why is sumSoFar = 0. This is a task from Learn Street.com

function sum(n) {
    var sumSoFar = 0;
    var currentNumber = 1;

    while (currentNumber <= n) {
        sumSoFar += currentNumber;
        currentNumber += 1;
    }

    return sumSoFar;
}

sumSoFar is initialized to zero at the start of the function because the rest of the function uses the += operator which takes the current value of sumSoFar and adds a value to that and then assigns the new value back to sumSoFar . If it wasn't initialized to zero, then it would not have an initial value and the first += operation on it would not have the desired result.

Initializing it to zero gives it the desired starting point so that the first time through the while loop, it adds currentNumber to that initial value of zero and assigns that to sumSoFar which is the desired behavior.

FYI, you can see your function work here: http://jsfiddle.net/jfriend00/kXrV8/ and in the latest version, you can try different input arguments to your sum(n) function.

如果未将sumSoFar初始化为零,则不能向其中添加值,因为它不是数字。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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