zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    LeetCode 560. Subarray Sum Equals K (子数组之和等于K)
    25、LinkedList特有方法
    24、List三个子类的特点
    23、数据结构之数组和链表
    22、Vector简介
    21、List遍历时修改元素的问题
    20、List集合中特有的方法
    19、集合概述
    18、Random类简介
    17、enum简介
  • 原文地址:https://www.cnblogs.com/Mr-Joe/p/4250066.html
Copyright © 2011-2022 走看看