简体   繁体   English

如何编写If / else语句?

[英]How to write If/else statement?

x = 1;    
if(x = 10) {x = 1;} 
else {x = x + 1;}
alert (x);

The result is always 1 , instead of 1,2,3... 结果始终为1 ,而不是1,2,3...

Replace 更换

if(x = 10) {x = 1;} 

with

if(x == 10) {x = 1;} 

Because x=10 returns 10 , which in a test evaluates as true, and thus the code {x = 1;} is executed. 因为x=10返回10 ,因此在测试中评估为true,因此执行代码{x = 1;}

From the MDN about if...else : MDN关于if ... else

Any value that is not undefined, null, 0, NaN, or the empty string (""), and any object, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement 任何未定义,空,0,NaN或空字符串(“”)的值,以及任何对象(包括值为false的布尔对象)在传递给条件语句时都将计算为true

x = 1;    
if(x 

== ==

10) {x = 1;} 
    else {x = x + 1;}
    alert (x);

if condition should be checked like below 是否应按以下方式检查条件

x=1;
if(x == 10)
{x = 1;}
else
{x = x+ 1;}
 alert(x)

Thanks 谢谢

var x = 1;
x = (x == 10)? 1:x+=1;
alert(x);

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

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