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

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

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

相关标签:
9条回答
  • 2020-11-22 07:38

    This one evaluates to the same but a bit smaller

    +!![]+''+(+[])
    
    • [] - is an array is converted that is converted to 0 when you add or subtract from it, so hence +[] = 0
    • ![] - evaluates to false, so hence !![] evaluates to true
    • +!![] - converts the true to a numeric value that evaluates to true, so in this case 1
    • +'' - appends an empty string to the expression causing the number to be converted to string
    • +[] - evaluates to 0

    so is evaluates to

    +(true) + '' + (0)
    1 + '' + 0
    "10"
    

    So now you got that, try this one:

    _=$=+[],++_+''+$
    
    0 讨论(0)
  • 2020-11-22 07:39
    ++[[]][+[]] => 1 // [+[]] = [0], ++0 = 1
    [+[]] => [0]
    

    Then we have a string concatenation

    1+[0].toString() = 10
    
    0 讨论(0)
  • 2020-11-22 07:39
    1. Unary plus given string converts to number
    2. Increment operator given string converts and increments by 1
    3. [] == ''. Empty String
    4. +'' or +[] evaluates 0.

      ++[[]][+[]]+[+[]] = 10 
      ++[''][0] + [0] : First part is gives zeroth element of the array which is empty string 
      1+0 
      10
      
    0 讨论(0)
提交回复
热议问题