简体   繁体   中英

Javascript: while loop that operates by boolean value creates infinite loop

I have a while loop that works when I use a condition such as while(x > 0) however when I change it to while(x == true) or while(x) it turns into an infinite loop despite me having a condition that changes the variable to false .

Here's how that part of my code is set up.

let appendNums = ['8','2','8','14'], //for testing purposes
    carryCheck = true,
    incAmount  = 0;

incAmount = appendNums.length - 1;

while(carryCheck){
  let currentNum = appendNums[incAmount];

  if(currentNum.length > 1){
    let numSplitter = currentNum.split(''),
        equation    = Number(appendNums[incAmount - 1]) + Number(numSplitter[0]);

    appendNums[incAmount]     = numSplitter[1];
    appendNums[incAmount - 1] = equation.toString();
    incAmount                 = incAmount - 1;
  }
  else{ carryCheck = false; break; }
}

Overall what's happening, is I'm working on a function to do addition the way we've been taught to do it on paper in school with "carrying the one over". I'm trying to tell the while loop to stop running when the .length of the current number is less than 2, indicating it's a single digit number and nothing else needs to be carried. In this instance the while(x > 0) way of doing it wouldn't work because it keeps running beyond where I want it to stop.

I double checked the syntax on MDN and have come across a few posts on here where people made the mistake of doing x = true instead of x == true or x === true . Can anyone spot what I'm doing wrong here?

UPDATE I just tried changing the while loop to while(appendNums[incAmount] > 1) and it still goes into an infinite loop.

Number(appendNums[incAmount - 1]) + Number(numSplitter[0]) will return NaN at some point because you do not check the array bounds.
By using equation.toString() and inserting it into appendNums[incAmount -1] , currentNum will always be the string "NaN" in the next iteration.
Since the string "NaN" has a length of 3, currentNum.length > 1 will always be true.

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