为什么在控制台中通过==的参数来改变输出? [英] Why does commuting the arguments of == in a console change the output?

查看:114
本文介绍了为什么在控制台中通过==的参数来改变输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我打开浏览器控制台(在Chrome / Firefox中测试)并输入:

If I open my browser console (tested in Chrome/Firefox) and type:

null == {}

我得到:


false

false

但是,如果我将两个参数都传递给 == 运算符,而是键入:

However, if I commute both arguments to the == operator and instead type:

{} == null

我得到:


未捕获的SyntaxError:意外的令牌==

Uncaught SyntaxError: Unexpected token ==

图片:


  • 为什么会这样?

  • 为什么这只发生在控制台中而不是当浏览器在HTML页面中执行脚本时?

编辑:

虽然问题35812626 解决了这个问题并解释了原因,因为JS解析了 {} 作为代码块,它使用三等于(严格比较)运算符 === ,而不是双等于 == 。正如用户在下面指出的那样,代码块肯定可以跟着 == ,而不会导致语法错误:

While question 35812626 addresses this and explains the cause as JS parsing the {} as a code block, it uses the triple equals (strict comparison) operator ===, not the double equals ==. As a user points out below, a code block can definitely be followed by == without causing a syntax error:

{} == {} // false

为什么会这样这是有效的,我的例子没有?

How come this works and my example does not?

推荐答案

我认为这是因为解释器解释 {} 作为不作为对象的代码块。

I think its because the interpreter interprets {} as a block of code not as an object.

所以你的代码 {} == null 结果是块开始和结束然后语句以 == 开头,这肯定是语法错误。

so your code {} == null turns out to be a block start and end then a statement starts with == which is definitely a syntax error.

但是如果你可以尝试({} == null)我认为应该可以正常运行。

but if you can try ({} == null) I think it should run fine.

和正如@dhaker所指出的那样 {} == {} 返回 false 并非错误。

and as pointed out by @dhaker {}=={} returning false not an error.

我发现很少有场景返回结果且很少收到错误。

and i found there are few scenario returning result and few getting error.

以下是收到错误:

{}==null //Uncaught SyntaxError: Unexpected token ==
{}==1 //Uncaught SyntaxError: Unexpected token ==
{}==0 //Uncaught SyntaxError: Unexpected token ==
{}==true //Uncaught SyntaxError: Unexpected token ==
{}==false //Uncaught SyntaxError: Unexpected token ==
{}==true //Uncaught SyntaxError: Unexpected token ==
{}=='' //Uncaught SyntaxError: Unexpected token ==
{}=='hi' //Uncaught SyntaxError: Unexpected token ==
{}==(new Object) //Uncaught SyntaxError: Unexpected token ==

以下是没有错误的返回结果:

following are returning result without an error:

{}=={} //false
{}==function(){} //false

所以我猜这与浏览器编译或解释Javascript的方式有关。

so i guess it has something to do with how the Javascript is compiled or interpreted by the browsers.

详细解答请查看以下答案。

for much detailed answer please check following answer.

ob的比较奇怪的行为ject literals

这篇关于为什么在控制台中通过==的参数来改变输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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