为了解决这个问题: [] + [] === ""
,
请问下 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:
- Assert: input is an ECMAScript language value.
-
If Type(input) is Object, then
- If PreferredType is not present, let hint be
"default"
. - Else if PreferredType is hint String, let hint be
"string"
. - Else PreferredType is hint Number, let hint be
"number"
. - Let exoticToPrim be ? GetMethod(input, @@toPrimitive).
-
If exoticToPrim is not undefined, then
- If hint is
"default"
, set hint to"number"
. - Return ? OrdinaryToPrimitive(input, hint).
- If PreferredType is not present, let hint be
- Return input.
自问自答
let methodNames be « "valueOf", "toString"
[]
,not a primitive,继续执行 toString 返回""
参考这里评论,之前看到上面回答,没注意到评论。。。
OrdinaryToPrimitive ( O, hint )
When the abstract operation OrdinaryToPrimitive is called with arguments O and hint, the following steps are taken:
"string"
or"number"
.If hint is
"string"
, then"toString"
,"valueOf"
».Else,
"valueOf"
,"toString"
».For each name in methodNames in List order, do
If IsCallable(method) is true, then