&& 和 ||
逻辑运算符 OR : a ||
b
运算规定: 先隐式转换为boolean
类型进行判断,如果a为false
,就持续向后执行直到最初,返回隐式转换为false
的表达式。如果中途有true
则间接返回隐式转换为true
的表达式
逻辑运算符 AND : a &&
b
运算规定: 先隐式转换为boolean
类型进行判断,如果a为true
,就持续向后执行直到最初,返回隐式转换为true
的表达式。如果中途有false
则间接返回隐式转换为false
的表达式
JS利用:
只显示有值的表达式
let a = '';let b = 'test';let c = 'cHello';let m = a || b || c;
判断数据是否为空,不为空继续执行表达式
let arr = null;arr && arr.forEach(item=>{ console.log(item);})
& 和 |
位运算:
将两个数转换为2进制之后将每个数字中的数位对齐,而后对每一位进行运算
运算符 OR : |
运算规定: 两个数位有一个为true
就返回true
,否则返回false
。
运算符 AND : &
运算规定: 两个数位全为true
才返回true
,否则返回false
。
JS利用:
判断数字奇偶
function f(n) { // 整数取余法 if (n % 2) { console.log("n是奇数"); } else { console.log("n是偶数"); } // 位运算 if(n & 1){ console.log("n是奇数"); } else { console.log("n是偶数"); }}
这两种办法运算进去都为数字 \( 1 \) 或 \( 0 \) ,if判断会主动转换成
boolean
值。数值取整
function integerConvert(n) { return (n | 0);}
留神:
这里取整形式为间接截取后面的整数数值,须要用到其余取整形式请应用Math函数。
取整 | 函数 |
---|---|
四舍五入 | Math.round() |
向上取整 | Math.ceil() |
向下取整 | Math.floor() |
详情参考:
https://www.w3school.com.cn/j...
https://www.jb51.net/article/...
https://www.cnblogs.com/xljzl...