问题描述
据我所知,逻辑&&
的作用如下:
As far as I know, The logical &&
works like the following
var test = false;
var foo = test && 42;
此代码将 42
分配给 foo
仅如果第一个条件被评估为 true
。所以在这个例子中, foo
将保持其当前值。
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;
现在, foo
从 test 。我很困惑。 空字符串是Javascripts falsy values 之一,那么为什么&&
运算符会在这种情况下失败?
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 ?
推荐答案
您已自行回答了您的问题。
You have answered your question yourself.
var foo = test && 42;
42
将被分配到 foo
仅当 test
评估为真。
42
will be assigned to foo
only if test
evaluated to true.
因此,如果 test
为空字符串(评估为false),则42将不会分配给 foo
, foo
将是空字符串。
So if test
is empty string (evaluated to false), 42 won't assigned to foo
, foo
will be the empty string.
这篇关于&安培;&安培;评估问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!