javascript {}+"" 与 ""+{}

1. {}+""

 相当于+"", 因为js解析器把{} 当做 block表达式。

 一元运算符+ 的规则是(http://es5.github.io/index.html#x11.4.6):

  1. Let expr be the result of evaluating UnaryExpression.

  2. Return ToNumber(GetValue(expr)).

  根据标准:

  "" ==>GetValue()--> "" ==>ToNumber()----> 0;

    1.执行GetValue (http://es5.github.io/index.html#x8.7.1) ,规则如下:

      If Type(V) is not Reference, return V.

    因此返回 "";

    2. 执行ToNumer(http://es5.github.io/index.html#x9.3):

       The MV of StringNumericLiteral ::: [empty] is 0.

    根据标准,因此空字符串"" 返回0;

  因此 : {}+"" //0;

2.  ""+{}

  标准中 二元运算符 加法规则如下:

  1. Let lref be the result of evaluating AdditiveExpression.

  2. Let lval be GetValue(lref).

  3. Let rref be the result of evaluating MultiplicativeExpression.

  4. Let rval be GetValue(rref).

  5. Let lprim be ToPrimitive(lval).

  6. Let rprim be ToPrimitive(rval).

  7. If Type(lprim) is String or Type(rprim) is String, then

    1. Return the String that is the result of concatenating ToString(lprim) followed byToString(rprim)

  8. Return the result of applying the addition operation to ToNumber(lprim) andToNumber(rprim). See the Note below 11.6.3.

  ""  =ToPrimitive=>"" =ToString=>""

  {} =ToPrimitive=>"[object Object]"=ToString=> "[object Object]";

  所以结果 ""+{}  //[object Object]

  备注 :ToPrimitive 如果是普通对象 会调用 对象的 valueOf方法。如果没有如果没有则调用 toString方法. 如果是Date对象,则会调用toString,如果没有则调用valueOf;

  相关网址:http://es5.github.io/index.html#x9.1

        http://es5.github.io/index.html#x8.12.8

原文地址:https://www.cnblogs.com/Mr-Joe/p/4250066.html