x = 1;
if(x = 10) {x = 1;}
else {x = x + 1;}
alert (x);
The result is always 1
, instead of 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.
From the MDN about 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
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);
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.