在JavaScript中,{}是否等于true?

3

有人能解释一下为什么在Javascript中,

alert({} == true) 显示 false

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

在if条件中有什么不同会改变结果?

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


3
这是在特定的浏览器上吗?我试了一下,但没有看到 alert('true') 的显示。 - Tchoupi
2
在Chrome 21中,它们都是false:http://jsfiddle.net/kq8QL/ - mellamokb
非常抱歉,各位,我第一次打错了,我的意思是 if ({}) alert('true')。你们回复得真快! - Cristi Mihai
一个空对象是真值,但根据“==”运算符的语义,并不“等于” true - Pointy
3
经过您的编辑,现在它完全变成了另外一回事。 if({}) 等价于 if ({} != false),而不是 if ({} == true)。这会让你获得一个奇怪的结果,见http://jsfiddle.net/kq8QL/1/。 - mellamokb
(obj || (obj = {})会导致ReferenceError错误。请使用(obj || {}),或者(obj || (obj={},obj))。那这和你的问题有什么关系呢? - KooiInc
5个回答

6

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

{}是一个对象,在if语句的上下文中被求值时,会被强制转换为一个Boolean值,由于Boolean({})的结果为true,因此得到了if (true)。这在ECMAScript规范的第12.5节 if语句中有所记录:

The production If Statement : if ( Expression ) Statement is evaluated as follows:

  1. Let exprRef be the result of evaluating Expression.
  2. If ToBoolean(GetValue(exprRef)) is false, return (normal, empty, empty).
  3. Return the result of evaluating Statement.

alert({} == true) -> false

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

比较x == y,其中x和y是值,产生true或false。 这样的比较执行如下:

如果Type(y)是布尔类型,则返回比较结果x == ToNumber(y)

因此,{} == true将被评估为{} == Number(true),这被评估为{} == 1,即false
这也是为什么1 == true评估为true,但2 == true评估为false的原因。

2

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

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

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

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

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

那么你的意思是 if(exp) statement 实际上是指 '如果 exp 不为假,则执行 exp'? - Cristi Mihai
基本上是的。除了一些会被解释为假的值,例如 nullundefined。或者 1 会被解释为 true,因为它可以转换为布尔类型的 true - Tchoupi

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进行比较时,它们的值不会被评估为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

0
alert({} == true) //display "false"

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

(片段)


0

我在jsfiddle.net上尝试了一下,只有在第一个警告框中显示false,IF语句没有弹出true。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接