jsfuck 6 个字符写 js 代码(二)

前文我们讨论了一下 JavaScript 数据类型转换的原理和几个基础的实例。下面,我们接着看一些 JavaScript 表达式实例,增强理解,为我们理解 JSFuck 的原理打下基础。

先来看 11 组简短的表达式:

(1) ![] + []
(2) ~[3]
(3) ~NaN
    ~Infinity
(4) ~[3,2]
(5) ~[]
(6) -~-~-~[]
(7) !"" + []
(8) 若 $ = [], _ = -~-~-~$, $_ = !"" + $
    $_[_/_] + $_[+$]
(9) ({} + [])[1]
(10) [1,2][0]
     [][0]
     Number([])
     [[]]
     [][[]]
(11) +[![]]

下面,我们一个一个地分析:

(1) ![] + []

![] + []
-> false + []
-> false + ""
-> "false"

(2) ~[3]

对字符串进行否运算 ~,JavaScript引擎会先调用Number函数,将字符串转为数值。
有个规律: 一个数与自身的取反值相加,等于-1

~[3]
-> ~(Number([3]))
-> ~(Number('3'))
-> ~3
-> -4

(3) ~NaN ~Infinity

~NaN
-> -1

~Infinity
-> -1

(4) ~[3,2]

~[3,2]
-> ~(Number([3,2]))
-> ~(Number('3,2'))
-> ~NaN
-> -1

(5) ~[]

~[]
-> ~(Number([]))
-> ~(Number(''))
-> ~0
-> -1

(6) -~-~-~[]

作为一元运算符时 - 和 ~ 运算符具有相同的优先级,右结合性。

-~-~-~[]
-> -~-~-(-1)
-> -~-~1
-> -~-(-2)
-> -~2
-> -(-3)
-> 3

(7) !”” + []

!"" + []
-> !"" + ""
-> true + ""
-> "true"

(8) $_[_/_] + $_[+$]

// 假设
// $ = [], _ = -~-~-~$, $_ = !"" + $

$_[_/_] + $_[+$]
-> "true"[3/3] + "true"[+[]]
-> "true"[1] + "true"[+""]
-> "true"[1] + "true"[0]
-> "r" + "t"
-> "rt"

(9) ({} + [])[1]

({} + [])[1]
-> "[object Object]"[1]
-> "o"

(10) 数组运算

[1,2][0]
-> 1

[][0]
-> undefined

Number([])
-> Number("")
-> 0

[[]]
-> [Array[0]]

[][[]]
-> undefined

[][[]] === [][0]
// true

(11) +[![]]

+[![]]
-> +[false]
-> Number([false])
-> Number('false')
-> NaN

下面再看一个稍微复杂些的表达式:

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

表达式比较长,我们拆开看:

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

分别计算:

// 一元运算符 + - ~ ! 优先级相同,右结合性

+!+[]
-> +!0
-> +true
-> 1

(!+[]+[])
-> !0 + []
-> true + ""
-> "true"

[!+[]+!+[]+!+[]]
-> [!0 + !0 + !0]
-> [true + true + true]
-> [3]

[+!+[]]
-> [+!0]
-> [+true]
-> [1]

[+[]]
-> [0]

所以,以上表达式相当于:

+(1 + "true"[3] + [1] + [0] + [0] + [0])
-> +(1 + "e" + 1 + 0 + 0 + 0)
-> +("1e1000")
-> 1e1000
-> Infinity

好了,暂时到这里,后面我们再继续这个话题。

参考:
[1] http://javascript.ruanyifeng.com/grammar/conversion.html
[2] http://www.jsfuck.com/
[3] https://gold.xitu.io/entry/5834a964570c35006c4ac205

views