Why does `{} + []` return a different result from `a = {} + []` in Javascript?

后端 未结 2 717
时光说笑
时光说笑 2020-12-19 03:33

In (at least) Firefox Web Console and JSBin, I get

> {} + []
0
> a = {} + []
\"[object Object]\"

Node.js returns \"[object Obje

2条回答
  •  一整个雨季
    2020-12-19 04:09

    When using an operator against objects the javascript interpreter should cast the values to primitive using the valueOf method which in fact use the internal ToPrimitive function relaying type casting to object's internal [[DefaultValue]] method.

    Your example with the plus operator is a bit tricky because the operator can acts both as math addition or string concatenation. In this case it concatenates string representations of the objects.

    What is really happening behind the scene is:

    a = {}.valueOf().toString() + [].valueOf().toString();
    

    Since the array is empty the toString method returns an empty string, that's why the correct result should be [object Object] which is the return value from object.valueOf()toString().

提交回复
热议问题