请问下 ecma 里 ToPrimitive([]) 怎么把hint 转成 string 的

为了解决这个问题: [] + [] === ""
请问下 ToPrimitive([]) 怎么把hint 转成 string 的

ToPrimitive ( input [ , PreferredType ] )

The abstract operation ToPrimitive takes an input argument and an optional argument PreferredType. The abstract operation ToPrimitive converts its input argument to a non-Object type. If an object is capable of converting to more than one primitive type, it may use the optional hint PreferredType to favour that type. Conversion occurs according to the following algorithm:

  1. Assert: input is an ECMAScript language value.
  2. If Type(input) is Object, then

    1. If PreferredType is not present, let hint be "default".
    2. Else if PreferredType is hint String, let hint be "string".
    3. Else PreferredType is hint Number, let hint be "number".
    4. Let exoticToPrim be ? GetMethod(input, @@toPrimitive).
    5. If exoticToPrim is not undefined, then

      1. Let result be ? Call(exoticToPrim, input, « hint »).
      2. If Type(result) is not Object, return result.
      3. Throw a TypeError exception.
    6. If hint is "default", set hint to "number".
    7. Return ? OrdinaryToPrimitive(input, hint).
  3. Return input.
阅读 2.2k
1 个回答

自问自答

  1. ToPrimitive set hint to number
  2. OrdinaryToPrimitive 第4步let methodNames be « "valueOf", "toString"
  3. 第5步[]先执行 valueOf 返回[],not a primitive,继续执行 toString 返回""

参考这里评论,之前看到上面回答,没注意到评论。。。

OrdinaryToPrimitive ( O, hint )

When the abstract operation OrdinaryToPrimitive is called with arguments O and hint, the following steps are taken:

  1. AssertType(O) is Object.
  2. AssertType(hint) is String and its value is either "string" or "number".
  3. If hint is "string", then

    1. Let methodNames be « "toString""valueOf" ».
  4. Else,

    1. Let methodNames be « "valueOf""toString" ».
  5. For each name in methodNames in List order, do

    1. Let method be ? Get(O, name).
    2. If IsCallable(method) is true, then

      1. Let result be ? Call(method, O).
      2. If Type(result) is not Object, return result.
  6. Throw a TypeError exception.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题