简体   繁体   中英

How to stop this for-loop?

var number = prompt("Typ some numbers:")
var som = 0

for (var x = 0; x < number.length; x++) {
  if (!(number[x] === 0)) {
    if ((number[x] % 2) === 1) {
      som += (number[x] * number[x])
    }
  } else {
    break;
  }
}

alert(som)

I want to type some random numbers (0-9) and then it must say the som of the Square of all the odd numbers before I type zero. For example I type: 5903. 5*5 + 9*9 = 106. So AFTER I type a zero it must STOP the for loop of going further. But right now if I typ 5903 it says 115, so right now it still DOES count 3*3 extra. So how do I make it stop after I type a zero? It doesn't work right now, it goes on after I type a zero. Someone know what's the problem? Maybe syntax?

Please change

if (!(number[x] === 0)) {

to

if (number[x] !== '0') {

because you are comparing strings.

Working example:

 var number = prompt("Typ some numbers:"), som = 0; for (var x = 0; x < number.length; x++) { if (number[x] !== '0') { if ((number[x] % 2) === 1) { som += (number[x] * number[x]); } } else { break; } } alert(som); 

you are checking if the number is equal to 0, but your number is actually '0'

you need to parse the input as an integer or you can use double equals

var number = prompt("Typ some numbers:");
var som = 0;

for (var x = 0; x < number.length; x++){
  if(number[x] == 0){
    break;
  }  
  if ((number[x] % 2) === 1) {
     som += (number[x] * number[x]);
  }

}

alert(som);

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