• js运算符单竖杠“|”的用法和作用及js数据处理


      很多朋友都对双竖杠“||”,了如指掌,因为这个经常用到。但是大家知道单竖杠吗?

      看JavaScript实用技巧,js小知识文章时,看到了单竖杠“|”运算,对它很陌生。

      学习并掌握它。

      js运算符单竖杠“|”的作用

      在js操作,Number | 0 的时候:

      a. 整数操作的时候,相当于去除小数点,parseInt。

      b. 正数的时候,相当于向下取整,Math.floor()。

      c. 负数的时候,相当于向上取整,Math.ceil()。

    Math.ceil() // 向上取整
    Math.floor() // 向下取整
    Math.round() // 四舍五入取整
    
    console.log(0.6|0) // 0
    console.log(1.1|0) // 1
    console.log(3.6555|0) // 3
    console.log(-5.22|0) // -5
    console.log(-7.777|0) // -7

      处理数字经常用到的方法还有:parseInt()、parseFloat()、toFixed()、toPrecision()

      toFixed(),保留几位小数,四舍五入,结果是字符串。

    100.456001.toFixed(2) // "100.46"
    100.456001.toFixed(3) // "100.456"
    Number.prototype.toFixed.call(100.456, 2) // "100.46"

      toPrecision(),保留几位数,四舍五入,结果是字符串。

    99.456001.toPrecision(5) // "99.456"
    100.456001.toPrecision(5) // "100.46"
    Number.prototype.toPrecision.call(10.456001, 5) // "10.456"

      单竖杠“|”的运算规则

      “Number|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进制之后相加得到的结果。

    console.log(3|4) // 7
    // 转换为二进制之后 011|110  相加得到111=7
    
    console.log(4|4) // 4
    // 转换为二进制之后 100|100  相加得到100=4
    
    console.log(8|3) // 11
    // 转换为二进制之后 1000|011  相加得到1011=11
    
    console.log(5.3|4.1) // 5
    // 转换为二进制之后 101|100  相加得到101=5

      

      

  • 相关阅读:
    ExtJS 4布局
    ExrJS4学习笔记1 类
    Jquery实现动态添加按钮
    ExtJs 4 MVC
    读取目录下所有目录和文件加载到TreeView
    利用List的Sort()、Find()、FindAll()、Exist()來解決一些問題
    html常用
    ExtJs3.3 TreePanel,checked节点和平常节点同时存在
    sql server 常用查询
    美女时钟网页代码
  • 原文地址:https://www.cnblogs.com/EnSnail/p/8124556.html
Copyright © 2020-2023  润新知