JS 对象空检查 - 奇怪的 JS 问题

JS object null checking - weird JS problem

想象一下这个简单的场景。我有一个变量,它可以是带有一个 属性、ID 的普通 JS 对象,它是一个数字,或者 obj 变量可以为空。我有一个简单的 test() 函数来检查变量是否不为 null 并且它必须具有有效的 id 属性.

var obj = { id: 111 };
function test() {
    return (obj && obj.id);
}

我希望这个函数总是 return 布尔值,但实际上如果 obj 是未定义的,它是 return 未定义的,或者如果对象存在的值是 obj.id 就像上面的情况一样.为什么这个函数 return 111 而不是 true.

我要扯掉头发了...请照亮我的心:)

定义了obj,为什么if (obj && obj.id) return 111

The logical AND (&&) operator returns expr1 if it can be converted to false; otherwise, returns expr2.

MDN: Logical Operators - Description(略有转述)

expr1 (obj) 无法转换为 false,因此 returns expr2 (111).


为什么不 return true?

Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || 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.

MDN: Logical Operators

因为您对非布尔值使用逻辑运算符,所以结果也将是非布尔值。

这是一个常见的误解。在 JS 中(与 PHP 不同)像 x && y 这样的表达式是这样的:

  1. 执行表达式x
  2. 如果表达式 x return 为真,则执行表达式 y 以及 和 return 它 (y )。否则 return x(在这种情况下是假的,例如 0''falsenullundefined) .

换句话说,它更像是一个三元表达式x ? y : z

如果你想要一个布尔值,那么使用!!(x && y)