How does x|0 floor the number in JavaScript?(x|0 如何对 JavaScript 中的数字进行下限?)
问题描述
在我之前的问题的已接受答案中( 最快的生成方式是什么javascript 中的随机整数? ),我想知道一个数字是如何通过符号 | 丢失小数的.
In the accepted answer on my earlier question
( What is the fastest way to generate a random integer in javascript? ), I was wondering how a number loses its decimals via the symbol |
.
例如:
var x = 5.12042;
x = x|0;
如何将数字设为5?
更多示例:
console.log( 104.249834 | 0 ); //104
console.log( 9.999999 | 0 ); // 9
推荐答案
因为根据 ECMAScript 规范,位运算符在每个要计算的表达式上调用 ToInt32.
Because, according to the ECMAScript specifications, bitwise operators operators call ToInt32 on each expression to be evaluated.
请参阅11.10 二进制位运算符:
产生式 A : A @B,其中 @ 是上面的产品,评估如下:
The production
A : A @B, where@is one of the bitwise operators in the productions above, is evaluated as follows:
评估
A.
调用GetValue(Result(1)).
评估B.
调用GetValue(Result(3)).
调用ToInt32(Result(2)).
调用ToInt32(Result(4)).
将位运算符 @ 应用于 Result(5) 和 Result(6).结果是一个有符号的 32 位整数.
Apply the bitwise operator @ to Result(5) and Result(6). The result is a signed 32 bit integer.
返回结果(7).
这篇关于x|0 如何对 JavaScript 中的数字进行下限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:x|0 如何对 JavaScript 中的数字进行下限?
- 400或500级别的HTTP响应 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
