作用:将数字向下取整
在 JavaScript 中,| 0 是一个常用的技巧,用于将数字向下取整。它的效果与 Math.floor() 相同,但对于负数,效果更像 Math.ceil()。它的好处是简洁和速度快,但有时可能会牺牲一些可读性。
快速检查一个数是否为整数
function isInteger(num) {return (num | 0) === num;}console.log(isInteger(4.9)); // falseconsole.log(isInteger(4)); // true
在数组中获取元素
可以用来快速计算索引:
const arr = [1, 2, 3, 4, 5];const index = 2.9;console.log(arr[index | 0]); // 3
实现循环数组
当你想要在数组中循环时,| 0 可以用来取模。
const arr = [1, 2, 3, 4, 5];let index = 7.9;console.log(arr[index % arr.length | 0]); // 3
快速转换字符串为整数
如果你有一个数字字符串并且你知道它是一个有效的数字,| 0 可以快速地转换它。
const strNum = "123";console.log(strNum | 0); // 123
注意:尽管 | 0 是一个强大和有用的技巧,但在某些情况下,它可能会导致代码的可读性降低。因此,确保你的团队成员都理解这个技巧,或者在使用它时添加适当的注释。
