来到杭州实习半个多月了,公司看了半个月的代码,发现代码来买使用好多的 逻辑运算,之前也学过但是用的不多,所以在对于逻辑的运算进行条件赋值有点懵逼,所以花了一点点时间看看其他博客,顺便做个总结
优先级
三个逻辑运算符(&&、||、!)优先级是:!、&& 、||
运算规则
在js逻辑运算中,0、”“、null、false、undefined、NaN都会判为false,其他都为true。
逻辑与(&&)和逻辑或(||)运算符都遵循短路原则。
返回值
逻辑与(&&)的运算规则,左右两者同为true时,为true;有一者为false时,为false。
逻辑与(||)的运算规则,左右两者同为false时,为false;有一者为true时,为true。
但是其返回值并非是返回布尔类型的true和false,而是返回其运算符左右两旁的一个值。
小技巧:
&& 运算:假前真后
||运算: 真前假后
逻辑与(&&)运算原则:A && B;
当A为true时,无论B是true或false,都会返回B。
当A为false时,无论B是true或false,都会返回A。
var a={};
var b=56;
window.key = undefined
console.log(window.key && null); //undefined
console.log(null && window.key); //null
console.log(a && null); //null
console.log(window.key && a); //undefined
console.log(a && b); //56
console.log(b && a); //object {}
逻辑或(||)运算原则:A || B;
当A为true时,无论B是true或false,都会返回A。
当A为false时,无论B是true或false,都会返回B。
var a={};
var b=56;
window.key = undefined
console.log(window.key || null); //null
console.log(null || window.key); //undefined
console.log(a || null); //object {}
console.log(window.key || a); //object {}
console.log(a || b); //object {}
console.log(b || a); //56
其他
位运算符:两个位只要有一个为1,那么结果都为1。否则就为0
31 | 2 //结果为31 十进制31 转化二进制为11111 2转化为二进制10
11111 | 00010 //结果为11111
位运算符:两个位只要有一个为1,那么结果都为1。否则就为0
31 & 2 //结果为31 十进制31 转化二进制为11111
11111 & 00010 //结果为10