妙用笔记JS中的骚操作

6次阅读

共计 408 个字符,预计需要花费 2 分钟才能阅读完成。

1. 使用 ^ 切换变量 1、0

// if 判断
if (toggle) {toggle = 1;} else {toggle = 0;}

// 三目运算符
togle = toggle ? 1 : 0;

// 位运算
toggle ^= 1;

2. 使用 !! 转为布尔值

console.log(!!7); // true
console.log(!!0); // false
console.log(!!-1); // true
console.log(!!0.71); // true

3. 使用 & 判断奇偶数

console.log(7 & 1); // 1 奇数
console.log(8 & 1) ; // 0 偶数 

4. 使 ~~ 取整

console.log(~~11.71)     // 11

5. 使用 ^ 判断数值是否同为正数或者同为负数

(a ^ b) >= 0; //  true 相同;  false 不相同 

6. 使用 1/0 来替代 Infinity

console.log(1/0)        // Infinty
console.log(-1/0)       // -Infinty
正文完
 0