简体   繁体   中英

Why can't I assign and then check a variable in the same if statement in Javascript?

In other words, why doesn't this show an alert?

var x;
if (x = 1 && x > 0) {
    alert(x);
}

As far as I understand, x = 1 should assign 1 to x and also return 1. The x > 0 check is failing. Why?

Actually, the && operation will have precedence over the assignment.

In you case, x will be the result of 1 && x > 0 which is false .

 var x; if (x = 1 && x > 0) { alert(x); } console.log(x); // false 

You can enforce the order of operations using parentheses, as shown by Nina Scholz .

You need some parens to separate the assignment from the ongoing expression.

 var x; if ((x = 1) && x > 0) { 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.

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