简体   繁体   English

如何停止此for循环?

[英]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. 我想输入一些随机数(0-9),然后在输入零之前必须说所有奇数的平方的平方。 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. 例如,我键入:5903。5 * 5 + 9 * 9 =106。因此,在键入零之后,必须停止for循环才能继续。 But right now if I typ 5903 it says 115, so right now it still DOES count 3*3 extra. 但是现在,如果我键入5903,它说的是115,那么现在它仍然要多加3 * 3。 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' 您正在检查数字是否等于0,但实际上是'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);

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

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