对象文字比较的奇怪行为

对象文字比较的奇怪行为

本文介绍了对象文字比较的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索过,但在JavaScript中找不到跟随的逻辑。

I have searched but could not find logic behind following in JavaScript.

当我输入Chrome控制台时:

When I type in the Chrome console:

{} == null

它返回

但是

{} == {}

{} == function(){}

返回false

为什么?

推荐答案

我假设你理解为什么 {} == null throws SyntaxError 。长话短说这是因为 {在开始一个块语句而不是对象文字的开头。你可以查看答案

I assume you understand why {} == null throws SyntaxError. Long story short it is because { in the begining starting a block statement not an object literal. You could check the answer here

至于为什么 {} == {} 这是有效的。

As of why {} == {} this works.

如果你检查铬代码来评估控制台中的表达式。您可以找到以下内容()

If you check chromium code that evaluates expressions in console. You could find the following (code)

if (/^\s*\{/.test(text) && /\}\s*$/.test(text))
    text = '(' + text + ')';
executionContext.evaluate(text, "console", !!useCommandLineAPI, false, false, true, printResult);

此代码包装 {} == {} 带括号的代码使其成为有效的表达式({} == {})比较两个空对象文字。其中的计算结果为 false ,因为对象是通过引用进行比较的。

This code wraps {} == {} code with parentheses making it a valid expression ({} == {}) comparing two empty object literals. Which evaluates to false because objects are compared by reference.

节点repl具有相同的行为

Node repl has the same behaviour 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;
}

这篇关于对象文字比较的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:04