Why does an assignment in an if statement equate to true?

五迷三道 提交于 2019-12-02 16:02:59

问题


Let me start off by saying I understand the difference between =, ==, and ===. The first is used to assign the right-hand value to the left-hand variable, the second is used to compare the equivalency of the two values, and the third is used not just for equivalency but type comparison as well (ie true === 1 would return false).

So I know that almost any time you see if (... = ...), there's a pretty good chance the author meant to use ==.

That said, I don't entirely understand what's happening with these scripts:

var a = 5;

if (a = 6)
	console.log("doop");

if (true == 2)
	console.log('doop');

According to this Javascript type equivalency table, true is equivalent to 1 but not 0 or -1. Therefore it makes sense to me that that second script does not output anything (at least, it isn't in my Chrome v58.0.3029.110).

So why does the first script output to the console but the second doesn't? What is being evaluated by the first script's if statement?

I dug into my C# knowledge to help me understand, but in C# you cannot compile if (a = 5) Console.WriteLine("doop"); so I had to explicitly cast it to a bool by doing if (Convert.ToBoolean(a = 5)) but then that makes sense it would evaluate to true because according to MSDN's documentation, Convert.ToBool returns true if the value supplied is anything other than 0. So this didn't help me very much, because in JS only 1 and true are equal.


回答1:


There's a difference between making an abstract equality comparison with == and performing a simple type cast to boolean from a number value. In a == comparison between a boolean and a number, the boolean value is converted to 0 or 1 before the comparison. Thus in

if (true == 2)

the value true is first converted to 1 and then compared to 2.

In a type cast situation like

if (x = 2)

the number is converted to boolean such that any non-zero value is true. That is, the value 2 is assigned to x and the value of the overall expression is 2. That is then tested as boolean as part of the evaluation of the if statement, and so is converted as true, since 2 is not 0.

The various values that evaluate to boolean false are 0, NaN, "", null, undefined, and of course false. Any other value is true when tested as a boolean (for example in an if expression).




回答2:


Why does an assignment in an if statement equate to true?

It doesn't. An assignment is evaluated as whatever value is assigned.

This expression is a true value:

a = true

But this expression is a false value:

b = false

That's true whether or not you put it in an if statement or not.



来源:https://stackoverflow.com/questions/44630882/why-does-an-assignment-in-an-if-statement-equate-to-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!