Why does !{}[true] evaluate to true in JavaScript?

前端 未结 10 1474
一个人的身影
一个人的身影 2020-12-12 17:55

{}[true] is [true] and ![true] should be false.

So why does !{}[true] evaluate to true

10条回答
  •  感动是毒
    2020-12-12 18:17

    {}[true] is undefined. To find that write this:

    a = {};
    a[true] === undefined // true
    

    or simply:

    ({})[true] === undefined // true
    

    We know that !undefined is true.


    From @Benjamin Gruenbaum's answer:

    Chrome dveloper tools does the following:

      try {
          if (injectCommandLineAPI && inspectedWindow.console) {
              inspectedWindow.console._commandLineAPI = new CommandLineAPI(this._commandLineAPIImpl, isEvalOnCallFrame ? object : null);
              expression = "with ((window && window.console && window.console._commandLineAPI) || {}) {\n" + expression + "\n}";
          }
          var result = evalFunction.call(object, expression);
          if (objectGroup === "console")
              this._lastResult = result;
          return result;
      } 
      finally {
          if (injectCommandLineAPI && inspectedWindow.console)
              delete inspectedWindow.console._commandLineAPI;
      }
    

    So basically, it performs a call on the object with the expression. The expression being:

    with ((window && window.console && window.console._commandLineAPI) || {}) {
        {}+{};// <-- This is your code
    }
    

    So, as you can see, the expression is being evaluted directly, without the wrapping parenthesis.

    More information can be found in this question.

提交回复
热议问题