&& evaluation issue

ぐ巨炮叔叔 提交于 2019-12-10 13:25:35

问题


As far as I know, The logical && works like the following

var test = false;
var foo = test && 42;

This code, will assign 42 to foo only if the first condition gets evaluated to true. So in this example, foo will keep its current value.

I'm wondering why this snippet doesn't work at all:

var test = "";
var foo = test && 42;

Now, foo gets the value from test assigned. I'm very confused. The empty string is one of Javascripts falsy values, so why would the && operator fail in this scenario ?

Can someone help me out with the spec on this one please ?


回答1:


You have answered your question yourself.

var foo = test && 42;

42 will be assigned to foo only if test evaluated to true.

So if test is empty string (evaluated to false), 42 won't assigned to foo, foo will be the empty string.




回答2:


You're misunderstanding the operator.
foo = x && y will always assign foo.

The && operator evaluates to its left-most "falsy" operand.

false && 42 evaluates to false; "" && 42 evaluates to "".

var foo = test && 42; assigns false to foo.



来源:https://stackoverflow.com/questions/12162157/evaluation-issue

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