分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

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

发布时间:2023-09-06 01:32责任编辑:胡小海关键词: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) // 0console.log(1.1|0) // 1console.log(3.6555|0) // 3console.log(-5.22|0) // -5console.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) // 7console.log(4|4) // 4console.log(8|3) // 11console.log(5.3|4.1) // 5console.log(9|3455) // 3455

  好像无规律可循。其实不是的,单竖杠“|”就是转换为2进制之后相加得到的结果。

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

  

  

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

原文地址:https://www.cnblogs.com/EnSnail/p/8124556.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved