JS

JS竖杠、双竖杠

Posted by fsanren on July 24, 2019

JS单竖杠的作用

这里介绍|的作用

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

其实单竖杠|就是转换为2进制之后相加得到的结果

- 3|4 
转换为二进制之后011|100 相加得到111=7 
- 4|4 
转换为二进制之后100 |100 相加得到100=4 
- 8|3 
转换为二进制之后1000 |011 相加得到1011=11

JS双竖杠的作用

var objOne = undefined || 1 || null || new Date();
var objTwo = new Date();
var objThree = objOne || objTwo;
alert(objThree.toString()); //out put "1"
  1. JS双竖线运算符: 是或比较.如null||'1'返回1, '2'||'1',返回2. 即或运算符中,第一个为真,后面的就不用计算了.所以得2。
  2. js 中 使用双竖线运算符||,返回第一个有效值

&& 对比 ||


let firstName = null;
let lastName = null;
let nickName = "Supercoder";

// shows the first defined value:
alert(firstName ?? lastName ?? nickName ?? "Anonymous"); // Supercoder
let firstName = null;
let lastName = null;
let nickName = "Supercoder";

// shows the first truthy value:
alert(firstName || lastName || nickName || "Anonymous"); // Supercoder

The important difference between them is that:

  • || returns the first truthy value.
  • ?? returns the first defined value.

tips: “defined” when it’s neither null nor undefined.

In other words, , || doesn’t distinguish between false, 0, an empty string "" and null/undefined. They are all the same – falsy values. If any of these is the first argument of ||, then we’ll get the second argument as the result.