單豎槓「|」的作用
在 JavaScript 中對數值做位運算時,「|」相當於去掉小數部分、只保留整數,效果類似 parseInt。具體而言:對正數而言相當於 Math.floor(),對負數而言相當於 Math.ceil()。補充:
1. Math.ceil() 向上取整;
2. Math.floor() 向下取整;
3. Math.round() 是我們數學中常用的四捨五入取整。
console.log(0.6|0)//0 console.log(1.1|0)//1 console.log(3.65555|0)//3 console.log(5.99999|0)//5 console.log(-7.777|0)//-7
除了 Math 的這幾個方法,我們還常用 parseInt()、parseFloat()、toFixed()、toPrecision() 等來處理數字。簡單說明:
toFixed 用法:
100.456001.toFixed(2); //100.47 100.456001.toFixed(3); //100.456 Number.prototype.toFixed.call(100.456001,2); //100.47
缺點:使用後會變成字串。
toPrecision 用法:
99.456001.toPrecision(5); //99.456 100.456001.toPrecision(5); //100.46 Number.prototype.toPrecision.call(10.456001,5); //10.456
單豎槓的運算規則
從上面的例子不難看出,單豎槓可以進行取整運算,只保留整數部分、丟掉小數部分。那麼「|0」為什麼能起到取整的作用呢?單豎槓不是 0 又是什麼結果?帶著這些問題看下面的例子:
console.log(3|4); //7 console.log(4|4);//4 console.log(8|3);//11 console.log(5.3|4.1);//5 console.log(9|3455);//3455
答案其實很簡單:單豎槓「|」是把數字轉為二進制後按位求或(對應位只要有一個為 1 則結果為 1)。舉例說明:
3|4:轉二進制後 011 | 100,按位或得到 111 = 7。
4|4:轉二進制後 100 | 100,按位或得到 100 = 4。
8|3:轉二進制後 1000 | 011,按位或得到 1011 = 11。
而「|0」之所以能取整,是因為與 0 做按位或時,整數部分保持不變、小數部分被直接截斷,於是最終只剩下整數部分。