为什么`{} == null`会产生SyntaxError错误? [英] Why does `{} == null` give a SyntaxError?

查看:73
本文介绍了为什么`{} == null`会产生SyntaxError错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将{}与true或false或它本身进行比较,但与null或undefined进行比较会产生语法错误.这是因为{}是对象值而不是引用吗?感觉很奇怪,这可能是语法错误,而不是某种运行时类型错误,或者只是可以正常工作.

I can compare {} to true or false or itself, but comparison to null or undefined gives a syntax error. Is this because {} is an object value and not a reference? It feels weird that it would be a Syntax Error instead of some kind of runtime type error, or just work.

为澄清起见,我很好奇为什么这是一个SyntaxError,与执行 {} == {} 相比,这不仅不是SyntaxError,而且根本没有错误.

To clarify, I'm curious why this is a SyntaxError, mostly compared to doing {} == {} which is not only not a SyntaxError, but no error at all.

推荐答案

解析代码时,主要有两个上下文:表达式上下文和语句上下文.例如,函数的主体是语句上下文,赋值的右侧是表达式上下文.区分两者是有道理的,例如:

There are two main contexts when parsing code: the expression context and the statement context. The body of a function for example is a statement context, the right side of an assignment is an expression context. To distinguish both makes sense to forbid things like:

 if( if(true) ) alert("nonsense");

现在REPL的任务非常艰巨:一方面,他们必须解析输入的函数和代码块,另一方面,您有时只想检查某个对象的外观.因此:

Now REPL have a really difficult task: On the one hand, they have to parse functions and codeblocks that get entered, and on the other hand you sometimes just want to check how a certain object look like. Therefore this:

 { a: 1, b: 2 }

实际上是JavaScript中的SyntaxError,因为语句上下文中的 {开始一个代码块,而:则无效.但是,REPL足够聪明,可以将该对象放入表达式上下文中,并对其进行评估,就像将其放在parens中一样:

is actually a SyntaxError in JavaScript, as a { in a statement context starts a block of code, and : is invalid then. However the REPL is clever enough and puts that object into an expression context, and evaluates it as if it would be in parens:

({ a: 1, b: 2 })

以下情况同样发生:

 {} == {}

实际上也是SyntaxError,但是REPL也会将其移入表达式上下文:

which is actually also a SyntaxError, however the REPL also moves it into an expression context:

 ({} == {})

移入表达式上下文"是一项复杂的任务,似乎REPL只是在这里看不到表达式:

That "moving into an expression context" is a complicated task, and it seems as if the REPL just does not see the expression here:

 {} == null

,因此将 {} 解析为一个块.之所以如此,是因为REPL只是天真地检查第一个和最后一个字符是否是 {} ,而 {} == {} ,但不能用于 {} == null .

and therefore parses {} as a block. Thats the case because the REPL just naively checks if the first and the last character are { and }, which is the case for {} == {} but not for {} == null.

铬源代码的相关部分:

 if (/^\s*\{/.test(text) && /\}\s*$/.test(text))
  text = '(' + text + ')';

executionContext.evaluate(text, "console", !!useCommandLineAPI, false, false, true, printResult);

这篇关于为什么`{} == null`会产生SyntaxError错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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