Objects and arrays addition

前端 未结 4 1739
抹茶落季
抹茶落季 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:27

    For {}+{}, the first {} is interpreted as a block, the second {} is interpreted as an empty object and the + is interpreted as a unary plus operator, so {}+{} is equivalent to:

    {
        //Empty block, does nothing
    }
    
    +{}    //Unary + applied to empty object, which is NaN
    

    Similarly, in {}+[], the {} is interpreted as a block and +[] is interpreted as the unary plus operator applied to an empty array, which gives 0.

    For []+{}, the + is interpreted as a string concatenation operator, so both the operands are converted to strings, in this case [] get converted to the empty string ("") and {} gets converted to "[object Object]", then both are concatenated together giving ""+"[object Object]" which is "[object Object]".

    Similarly, for []+[], both arrays get converted to the empty string, giving ""+"" which is "".

    0 讨论(0)
  • 2020-11-27 07:31

    Here is a full explanation of this, check it.

    And note {} + {} be NaN if you execute it directly in the console because {} is thought of a block rather than an object.

    ({}+{}) should be '[object Object][object Object]'

    The real result is:

    console.log({}+{}) // '[object Object][object Object]'
    console.log([]+{}) // '[object Object]'
    console.log({}+[]) // '[object Object]'
    console.log([]+[]) // ''
    
    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2020-11-27 07:40
    {} + {} 
    

    you can't make an addition or any operation on two object

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

    it's just a concat between a string and a object, you have the same result with alert({});

    {} + [] // 0
    

    same

    [] + [] // ""
    

    concat of two empty string = empty string.

    0 讨论(0)
提交回复
热议问题