Obfuscated javascript code with binary values?

前端 未结 3 1234
面向向阳花
面向向阳花 2021-01-02 02:02

This code outputs D. The question is HOW?

alert([][(![]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[         


        
3条回答
  •  情书的邮戳
    2021-01-02 02:39

    Well, evaluating the expression in parts, at the end it is equivalent to:

    []['sort']['call']()["btoa"]("00")[1]; // "D"
    

    Which can be simplified to :

    btoa("00")[1]; // "D"
    

    How you can "decode it"?

    Simply examine the operators used, for example, we can see at first that an array literal is used, then several bracket notation property accesses are done, and a couple of invocations.

    How does it work?

    The trick is to chain multiple type conversions, for example, to get the f letter:

    (![]+[])[+[]]
    

    If we examine the first part, in parentheses, ![]+[], we see a boolean negation, which will return false because an array object is always truthy, and then a concatenation.

    That produces the string "false", then, the second part, we see a brackets applied to that string, to access a character, and the expression +[], which results in 0.

    +[] gives zero because the Array's toString method returns an empty string, for an empty array like that one, and an empty string produces to zero when it is converted to number (the unary + operator in this example).

    There are just tricks like that, things that produce a string, such "true", "false", "null", "undefined", etc... and more tricks to get the numerically.

    For example to get a number -to access a character-, they use again cryptic type conversion:

    +[];            // 0, equivalent to +""
    +!+[];          // 1, equivalent to +true
    !+[]+!+[];      // 2, equivalent to +true+true
    !+[]+!+[]+!+[]; // 3, equivalent to +true+true+true
    

提交回复
热议问题