简体   繁体   English

确定奇/偶数,并使用While循环从Javascript计数器中添加

[英]Determine an Odd/even Number, And Use While Loop To Add From Counter in Javascript

I do not know why it stops looping after satisfying the condition sometime(eg.getting the sum of number from where it precedes). 我不知道为什么有时满足条件后它会停止循环(例如,从前面的位置获取数字的总和)。 I believe that there's something wrong with the code. 我认为代码有问题。 Where is it? 它在哪里?

var init = parseInt(prompt('enter an odd or even no.'));
var sec = init%2;

if (sec != 0) {
    var loop = 5;   
    while (loop < 10) {
        var num = 1;
        loop += loop; 
        num += 2
    }
    document.write(num);
} else {
    document.write('None');
}   

Is this what you are trying to do? 这是您要做什么? Variables declared with var don't have block scope, so it can be clearer to declare them all at the top of your code. var声明的变量没有块作用域,因此可以在代码的顶部声明所有变量。

 var init = parseInt(prompt('enter an odd or even no.')); var sec = init % 2; var loop = 5; var num = 1; if(sec != 0) { while(loop < 10) { num+=2; loop++; document.write(num); } } else { document.write('None'); } 

The looping is happening, but you're just not seeing it because you don't print anything when it loops. 循环正在发生,但是您只是看不到它,因为在循环时您什么都不打印。

Your code should be like this instead: 您的代码应改为:

var init = parseInt(prompt('enter an odd or even no.'));
var sec = init%2;

if (sec != 0) {
    var loop = 5;   
    while (loop < 10) {
        var num = 1;
        loop += loop; 
        num += 2
        document.write(num);
    }

} else {
    document.write('None');
} 

See that document.write(num) now is INSIDE your loop, so it will print every time it loops through. 看到document.write(num)现在位于循环内部,因此它将在每次循环时打印。

Previously, it was set outside, so essentially what was happening is that you were only seeing the result AFTER the last iteration. 以前,它是在外部设置的,因此本质上是在最后一次迭代之后才看到结果。

You need to initialize num with 1 outside of the while statement, because you assign this value for every loop. 您需要在while语句之外用1初始化num ,因为您需要为每个循环分配该值。

The I suggest to declare all variable in advane at top of the code. 我建议在代码顶部先声明所有变量。 You may assign here known values, too. 您也可以在此处分配已知值。

 var init = parseInt(prompt('enter an odd or even no.'), 10), sec = init % 2, loop = 5, num = 1; if (sec != 0) { while (loop < 10) { loop += loop; num += 2; } document.write(num); } else { document.write('None'); } 

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

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