关于javascript:JS中-和-的使用

1次阅读

共计 900 个字符,预计需要花费 3 分钟才能阅读完成。

&& 和 ||

逻辑运算符 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…

正文完
 0