We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
很多朋友都对双竖杠“||”,了如指掌,因为这个经常用到。但是大家知道单竖杠吗?今天有个网友QQ问我,我的 javascript实用技巧,js小知识 , 这篇文章里面,js整数的操作运用了单竖杠,问我单竖杠是啥意思?
我看了一下之前的那篇文章,只写了用法,但是并没有解释。好吧,我现在就给大家简单的介绍一下:
之前文章,在js整数操作的时候,相当于去除小数点,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
看了上面的例子,大体知道单竖杠可以进行取整运算,就是只保留正数部分,小数部分通过拿掉,但是“|0”,又是如何进行运算的呢,为什么能“|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
好像无规律可以寻找啊?网上搜索吧。http://tool.oschina.net/commons?type=6
这里面提到了单竖杠“|”但是没有javascript的。
好吧,我在这里公布答案吧。其实单竖杠“|”就是转换为2进制之后相加得到的结果。例如我们拿简单的举例:
3|4 转换为二进制之后011|100 相加得到111=7 4|4 转换为二进制之后100 |100 相加得到100=4 8|3 转换为二进制之后1000 |011 相加得到1011=11
以此类推,我在这里就不一一列举了,单竖杠“|”运算就是转换为2进制之后相加得到的结果!
The text was updated successfully, but these errors were encountered:
No branches or pull requests
js运算符单竖杠“|”的作用
很多朋友都对双竖杠“||”,了如指掌,因为这个经常用到。但是大家知道单竖杠吗?今天有个网友QQ问我,我的 javascript实用技巧,js小知识 , 这篇文章里面,js整数的操作运用了单竖杠,问我单竖杠是啥意思?
我看了一下之前的那篇文章,只写了用法,但是并没有解释。好吧,我现在就给大家简单的介绍一下:
之前文章,在js整数操作的时候,相当于去除小数点,parseInt。在正数的时候相当于Math.floor(),负数的时候相当于Math.ceil()
注:
单竖杠的运算规则
看了上面的例子,大体知道单竖杠可以进行取整运算,就是只保留正数部分,小数部分通过拿掉,但是“|0”,又是如何进行运算的呢,为什么能“|0”能达到取整的目的呢?单竖杠不是0有会是多少呢?
带着这些问题,我们看下面例子:
好像无规律可以寻找啊?网上搜索吧。http://tool.oschina.net/commons?type=6
这里面提到了单竖杠“|”但是没有javascript的。
好吧,我在这里公布答案吧。其实单竖杠“|”就是转换为2进制之后相加得到的结果。例如我们拿简单的举例:
以此类推,我在这里就不一一列举了,单竖杠“|”运算就是转换为2进制之后相加得到的结果!
The text was updated successfully, but these errors were encountered: