为什么{} == false抛出异常? [英] Why does {} == false throw an exception?

查看:173
本文介绍了为什么{} == false抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在IE和Chrome中,在JavaScript控制台中输入一个例外:

In IE and Chrome, typing this into the JavaScript console throws an exception:

{} == false   // "SyntaxError: Unexpected token =="

然而,所有这些语句都被评估没有问题: p>

However, all of these statements are evaluated with no problem:

false == {}   // false

({} == false) // false

var a = {};
a == false    // false

这是有意的行为吗?为什么会发生这种情况?

Is this intentional behavior? Why does this happen?

推荐答案

在控制台中,当您使用 {} ,您不是创建一个对象字面值,而是一个代码块(即与如果语句或循环体)所使用的块相同。然后,显然不需要像 == 这样的符号。

In the console, when you start a statement with {}, you are not creating an object literal, but a code block (i.e. the same block as you would make with an if statement or a loop body). A symbol like == is then obviously not expected afterwards.

如果你想到一个代码块,你知道

If you think of a code block, you know that something like a = 5; could come after it:

if (some_condition) {
    // do something
}
a = 5;

然后,您可以使用它在控制台中进行测试,并发现它工作正常:

You can then use this to test in the console, and find that it works just fine:

{} a = 5;

这篇关于为什么{} == false抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆