我已搜索但无法找到 JavaScript 中跟随背后的逻辑。
当我在 Chrome 控制台中输入时:
{} == null
返回
Uncaught SyntaxError: Unexpected token ==
但是
{} == {}
和
{} == function(){}
返回错误
为什么?
最佳答案
我假设您理解为什么 {} == null
会抛出 SyntaxError
。长话短说,这是因为 {
一开始是 block 语句而不是对象文字。你可以查看答案 here
至于为什么 {} == {}
这行得通。
如果您检查在控制台中计算表达式的 Chrome 代码。您可以找到以下内容 ( code )
if (/^\s*\{/.test(text) && /\}\s*$/.test(text))
text = '(' + text + ')';
executionContext.evaluate(text, "console", !!useCommandLineAPI, false, false, true, printResult);
此代码用括号包裹 {} == {}
代码,使其成为比较两个空对象文字的有效表达式 ({} == {})
。其计算结果为 false
,因为对象是通过引用进行比较的。
节点 repl 具有相同的行为 src
if (/^\s*\{/.test(code) && /\}\s*$/.test(code)) {
// It's confusing for `{ a : 1 }` to be interpreted as a block
// statement rather than an object literal. So, we first try
// to wrap it in parentheses, so that it will be interpreted as
// an expression.
code = `(${code.trim()})\n`;
wrappedCmd = true;
}
关于javascript - 对象文字比较的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50989247/