{} + [] - why it is 0 or [object Object]?

后端 未结 4 871
情深已故
情深已故 2020-12-31 04:45

If you open a JS Console in your browser (in my case Chrome) and type:

{} + []

you will get 0, but when you type

console.lo         


        
相关标签:
4条回答
  • 2020-12-31 05:00

    Empty object as {} returns "[object Object]" when you call its toString() method. Empty array returns "" when you call its toString() method. Thus, console.log({} + []) will output "[object Object]"

    0 讨论(0)
  • 2020-12-31 05:08

    it's because {} is an object notation so whatever you concatenate with {} it will give you an [object Object]. I your case [] is an empty so it just shows an [object Object]. so if you could try the following you will got what you want.

     console.log({} + 5);
     [object Object]5  ///console shows 
          //And
    console.log({} + "test");
    VM65:1 [object Object]test //console shows
    
    0 讨论(0)
  • 2020-12-31 05:19

    {} can either be an empty block or a empty object literal depending on context.

    + can either be the unary plus operator or the concatination operator depending on context.

    The first code example is an empty block it might as well not be there, making the expression the same as +[], meaning "An empty array converted to a number".

    You can't have a block as a function argument, so the second code example {} is an object and the code means "Concatinate an object with an array" (implicitly converting both object and array to strings).

    0 讨论(0)
  • 2020-12-31 05:21

    When you see {} character at the beginning it is interpreted as a empty block or empty object literal(when you're creating objects).

    When you're using an expression or statement, + represent the plus operator, which coerces its operand(in this case it will be []) to a number.

    So +[] is the same as Number([]), which evaluates to 0.

    The unary plus operator internally use the ToNumber abstract operation.

    Read more about Type Conversions and operators.

    console.log(Number([]));

    With the other words, {} + [] expression is an empty code block followed by an array which will be constraint to a number(Number[]).

    In the second example you're providing you just concat an object literal(empty object) to an array. That't why you're receiving [object Object].

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