{} == 在 javascript 中是否为真

Is {} == true or not in javascript?

本文关键字:是否 javascript      更新时间:2023-09-26

有人可以解释为什么在javascript中,

alert({} == true)显示错误

if ({}) alert('true')显示真实

更改结果的 if 条件有何不同?

我想写一些速记论证验证器obj || (obj = {});,我对这个发现感到困惑。

if ({}) alert('true') -> true

{}是一个对象,当在if语句的上下文中求值时,它被强制到Boolean,并且由于Boolean({})的计算结果为true,所以你会得到if (true)。这记录在 ECMAScript 规范的第 12.5 节 if 语句中:

生产 If 语句:求值 if (表达式( 语句 如下:

  1. 让 exprRef 成为计算表达式的结果。
  2. 如果 ToBoolean(GetValue(exprRef(( 为 false,则返回 (normal, empty, empty(。
  3. 返回评估语句的结果。

alert({} == true) -> false

这个更棘手。来自 ECMAScript 规范,第 11.9.3 节抽象相等比较算法

比较 x == y,其中 x 和 y 是值,产生真或假。此类比较按如下方式执行:

如果 Type(y( 是布尔值,则返回比较结果 x == ToNumber(y(。

因此,{} == true将被评估为 {} == Number(true),其计算为 {} == 1,即false

这也是为什么1 == true的计算结果是true,而2 == true的评估结果是false

{}不是

true,所以它不会出现在你的第一个示例中。在第二个示例中,{}不是假的,因此它将通过测试。

就像我的老师常说的,你不能拿土豆和胡萝卜来比较。

它不仅适用于数组,还可以与任何东西一起使用:

alert(3 == true); // shows false
if (3) alert('true'); // shows true

在布尔运算中,通常任何不0计算结果为 true。http://jsfiddle.net/QF8GW/

if (0) console.log("0 shows true"); // does not log a value
if (-1) console.log("-1 shows true");
if (12345) console.log("12345 shows true");
if ({}) console.log("{} shows true");
if ([]) console.log("[] shows true");

0之外的所有这些都将计算为 true。

但是,与true相比,它们的值不会评估为true

// logs the statement (1 and true are the same.)
​if (1 == true) console.log("1==true shows true");​​​​​​​​
if (12345 == true) console.log("12345==true shows true"); // does not log

我在 jsfiddle.net 中尝试过,只在第一个警报中尝试说假,IF没有提醒真。

alert({} == true) //display "false"
if({} == true)
{
   alert("it's true");
}else
{
   alert("it's false"); // <-- alert this
}

( 片段 (