javascript - 使用短路逻辑运算符测试空对象

标签 javascript variable-assignment logical-operators control-structure

我正在通读 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/

相关文章:

javascript - 在 JavaScript 中将最低有效数字移出十六进制序列

javascript - 如何使用 jQuery 或 JavaScript 获取 div ID 的一部分

javascript - 在我的案例中如何检测 div 冲突?

Kotlin 可空变量赋值

javascript - 使用解构的动态命名值

conditional - 我可以简化这个使用逻辑否定运算符的条件语句吗?

javascript - 谷歌地图重新开放模式问题

javascript - 当鼠标移动到带有jquery的文本上时显示图片?

c# - 在表达式中使用赋值可以吗?

python - 检查两个条件是否为真最快的方法是什么?