# JavaScript骚操作

5种方式实现值交换

``````1. var temp = a; a = b; b = temp; (传统，但需要借助临时变量)
2. a ^= b; b ^= a; a ^= b; (需要两个整数)
3. b = [a, a = b][0] (借助数组)
4. [a, b] = [b, a]; (ES6，解构赋值)
5. a = a + b; b = a - b; a = a - b; (小学奥赛题)
``````

``````parseInt(num)
~~numnum >> 0num | 0
``````

``````function isInt(x) { return (x ^ 0) === x
}
// return Math.round(x) === x
// return (typeof x === 'number') && (x % 1 === 0)
// ES6 -> Number.isInteger()
``````

``````function factorial(n) { return (n > 1) ? n * f(n - 1) : n
}
``````

``````function sameSign(a, b) { return (a ^ b) >= 0}
``````

``````arr.slice(0)
``````

``````// ES6Array.from(new Set(arr))// ES5arr.filter(function(ele, index, array){ return index===array.indexOf(ele)
})
``````

``````function maxArr(arr) { return Math.max.apply(null, arr)
}
``````

``````function minArr(arr) { return Math.min.apply(null, arr)
}
``````

``````function randomOne(arr) { return arr[Math.floor(Math.random() * arr.length)]
}
``````

``````function getRandomColor() { return `#\${Math.random().toString(16).substr(2, 6)}`}
``````

``````function randomStr(n) { let standard = 'abcdefghijklmnopqrstuvwxyz9876543210'
let len = standard.length let result = ''
for (let i = 0; i < n; i++) {
result += standard.charAt(Math.floor(Math.random() * len))
} return result
}
``````

``````JSON.parse(JSON.stringify(obj))
``````

``````console.log(([][[]] + [])[+!![]] + ([] + {})[!+[] + !![]])
console.log((!(~+[]) + {})[--[~+''][+[]] * [~+[]] + ~~!+[]] + ({} + [])[[~!+[]] * ~+[]])

console.info("%c哈哈", "color: #3190e8; font-size: 30px; font-family: sans-serif");

``````

382 声望
14 粉丝