Why does ++[[]][+[]]+[+[]] return the string “10”?

后端 未结 9 2178
傲寒
傲寒 2020-11-22 06:50

This is valid and returns the string \"10\" in JavaScript (more examples here):

9条回答
  •  耶瑟儿~
    2020-11-22 07:29

    Perhaps the shortest possible ways to evaluate an expression into "10" without digits are:

    +!+[] + [+[]] // "10"

    -~[] + [+[]] // "10"

    //========== Explanation ==========\\

    +!+[] : +[] Converts to 0. !0 converts to true. +true converts to 1. -~[] = -(-1) which is 1

    [+[]] : +[] Converts to 0. [0] is an array with a single element 0.

    Then JS evaluates the 1 + [0], thus Number + Array expression. Then the ECMA specification works: + operator converts both operands to a string by calling the toString()/valueOf() functions from the base Object prototype. It operates as an additive function if both operands of an expression are numbers only. The trick is that arrays easily convert their elements into a concatenated string representation.

    Some examples:

    1 + {} //    "1[object Object]"
    1 + [] //    "1"
    1 + new Date() //    "1Wed Jun 19 2013 12:13:25 GMT+0400 (Caucasus Standard Time)"
    

    There's a nice exception that two Objects addition results in NaN:

    [] + []   //    ""
    [1] + [2] //    "12"
    {} + {}   //    NaN
    {a:1} + {b:2}     //    NaN
    [1, {}] + [2, {}] //    "1,[object Object]2,[object Object]"
    

提交回复
热议问题