3

有人可以用javascript解释为什么,

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

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

改变结果的 if 条件有什么不同?

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

4

5 回答 5

6

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

{}是一个对象,当在if语句的上下文中评估时,它被强制转换为 a Boolean,并且由于Boolean({})评估为true,你得到if (true). 这记录在 ECMAScript 规范的第12.5 节 if 语句中:

产生式 If 语句 : if ( 表达式 ) 语句的评估如下:

  1. 令 exprRef 为计算表达式的结果。
  2. 如果ToBoolean(GetValue(exprRef))为 false,则返回(正常、空、空)。
  3. 返回 Statement 的评估结果。

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

于 2012-08-30T20:40:44.063 回答
2

{}并非true如此,它不会出现在您的第一个示例中。在您的第二个示例{}中不是错误的,因此它将通过测试。

就像我的老师曾经说过的那样,你不能比较土豆和胡萝卜。

它不仅适用于数组,它适用于任何东西:

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

if (3) alert('true'); // shows true
于 2012-08-30T19:58:14.630 回答
2

在布尔运算中,通常任何不0计算为真的东西。 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

// 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
于 2012-08-30T20:00:46.470 回答
0
alert({} == true) //display "false"

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

(片段)

于 2012-08-30T19:58:31.723 回答
0

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

于 2012-08-30T20:01:17.360 回答