交换两个变量值
已有两个变量 a,b,交换两个变量的值
临时变量法
var temp = a
a = b
b = temp
算数方法
可能导致溢出,不推荐
a = a + b
b = a - b
a = a - b
异或方法
a = a^b
b = a^b
a = a^b
ES6解构
[a,b] = [b,a]
利用数组特性
a = [a,b]
b = a[0]
a = a[1]
Comments
已有两个变量 a,b,交换两个变量的值
var temp = a
a = b
b = temp
可能导致溢出,不推荐
a = a + b
b = a - b
a = a - b
a = a^b
b = a^b
a = a^b
[a,b] = [b,a]
a = [a,b]
b = a[0]
a = a[1]