我正在通读 Mozilla Developer Network's page on Javascript ,并被我看到的一条线弄糊涂了。这是有问题的描述和行:
The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:
var name = o && o.getName();
我在这里的困惑是,大概该片段的目的是执行:
var name;
if (o){
name = o.getname();
}
但是,看起来这里发生的是 name 被分配了一个 bool 值,并且该 bool 值是“o 存在并且它的名称不为空”。换句话说,对我来说它看起来像:
var name = false;
if (o && o.getname()){
name = true;
}
谢谢!
最佳答案
这个答案是Felix Kling的评论我希望他将其发布为自己的答案以获得奖励的声誉
看看Logical Operators ,在最顶端:
"Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value."
关于javascript - 使用短路逻辑运算符测试空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23345029/