Objects and arrays addition

前端 未结 4 1753
抹茶落季
抹茶落季 2020-11-27 07:17

Can anyone explain to me how the results of the following was evaluated?

{} + {} // NaN
[] + {} // \"[object Object]\"
{} + [] // 0
[] + [] // \"\"
         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 07:33

    Adding arrays with any object and its string representation always results in a join

    For example:

    [1] + [2] // is merged to "12", so [] + [] is an empty string ""
    

    The same equals for your second example

    ['test'] + {} // "test[object Object]"
    

    So an empty array plus an empty object will just return an [object Object]


    For adding to empty objects it's easy too:

    Evaluate a simple empty object: {} // results in undefined

    And adding two undefined values is NaN because there's no way you can make an addition on them.

    Note: The return values depend on the implementation of JavaScript (i.e. in which Browser or Environment)

    Also: What is {} + {} in JavaScript?

提交回复
热议问题