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

后端 未结 4 895
情深已故
情深已故 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: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].

提交回复
热议问题