admin管理员组文章数量:1326304
I'm trying to print all even numbers from 10 to 40 using just a while loop in Javascript. But when I execute the code in the Chrome Browser console I only see 10. Here is my code:
var x = 10;
while (x !== 41 && x % 2 == 0){
console.log(x)
x++
}
I'm trying to print all even numbers from 10 to 40 using just a while loop in Javascript. But when I execute the code in the Chrome Browser console I only see 10. Here is my code:
var x = 10;
while (x !== 41 && x % 2 == 0){
console.log(x)
x++
}
Share
Improve this question
edited Oct 7, 2019 at 13:11
GBouffard
1,1074 gold badges11 silver badges25 bronze badges
asked Oct 7, 2019 at 11:48
I_am_a_NoobI_am_a_Noob
111 silver badge3 bronze badges
2
-
1
The loop stops as soon as
x % 2 == 0
isfalse
, before you reach the point whenx !== 41
isfalse
. – VLAZ Commented Oct 7, 2019 at 11:50 -
Just a quick note on while loops, conditions that break on strict equality are not the best.
x !== 41
would be better done asx < 41
. – Keith Commented Oct 7, 2019 at 11:55
4 Answers
Reset to default 4The problem is the x % 2 == 0
part. As soon as x
bees 11
the loop exits, because that condition evaluates to false
. For the loop to continue, both conditions inside the while()
parantheses have to evaluate to true
as you are using the &&
operator.
You should move that specific condition to an if
statement inside the loop, like so:
var x = 10;
while (x !== 41) {
if (x % 2 == 0)
console.log(x);
x++;
}
The solution above keeps going until x
is 41
in which case it will exit the loop and only runs the console.log(x)
statement, if x % 2
is equal to 0
(x
is even).
A tip I would like to give you is to make a habit of using ===
instead of ==
. This will ensure your value is of the correct type (e.g. x == 2
is true
when x
is "2"
but x === 2
will return false
as the type is different) and might help you catch a few errors when debugging.
Another tip would be to use x < 41
instead of x !== 41
, it's more monly used and it is easier to read through for most people.
As you are incrementing x
by one, at first iteration the value of x
bees 11(odd) and the while condition is breaking. You can increment x by 2 as below.
var x = 10;
while (x <= 40){
console.log(x);
x += 2;
}
x = 10;
while(x < 41) {
if(x % 2 == 0) {
console.log(x);
}
x++;
}
As you increase the i one by one, the value of the i bees 11 (odd) on the first iteration, while the level breaks. Can be increased by i 2 as shown below.
i = 10
while (i < 40) {
i += 2;
document.write("<br>",i);
console.log(i)
}
版权声明:本文标题:I'm trying to print all even numbers from 10 to 40 using just a while loop in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742206548a2432922.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论