x | 0如何在JavaScript中输入数字? [英] How does x|0 floor the number in JavaScript?
问题描述
在我之前的问题上接受的答案
(在javascript中生成随机整数的最快方法是什么?),我想知道一个数字如何通过符号 | $ c丢失其小数$ c>
。
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(结果(1))
。
评估 B
。
致电 GetValue(结果(3))
。
致电 ToInt32(结果(2))。
Call ToInt32(Result(2)).
致电 ToInt32(结果(4))。
Call ToInt32(Result(4)).
将按位运算符 @
应用于结果(5)
和结果(6)
。 结果是带符号的32位整数。
Apply the bitwise operator @
to Result(5)
and Result(6)
. The result is a signed 32 bit integer.
返回结果(7)
。
这篇关于x | 0如何在JavaScript中输入数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!