2012-01-28 14 views
9

在我早期問題 (What is the fastest way to generate a random integer in javascript?)的接受答案中,我想知道數字如何通過符號| 丟失小數。x | 0如何在JavaScript中設置數字?

例如:

var x = 5.12042; 
x = x|0; 

這是如何樓層數5

一些例子:

console.log(104.249834 | 0); //104 
console.log(9.999999 | 0); // 9 
+2

您應該知道,使用按位運算符會將您限制爲32位有符號整數。 '((Math.pow(2,32)/ 2)-1)| 0; // 2147483647'刪除'-1',你不會得到想要的結果。 '((Math.pow(2,32)/ 2))| 0; // -2147483648' – 2012-01-28 23:57:34

+0

有趣。這可能是這個函數比'Math.floor(x)'函數稍快的原因。 http://jsperf.com/floor-or-or – user824294 2012-01-30 03:01:35

+1

實際上並沒有 '地板',嘗試用'-1.23'看個究竟 – ajax333221 2012-06-05 03:53:14

回答

13

因爲,根據ECMAScript的規範,位運算符運營商呼籲ToInt32上進行評估的每個表情。

參見11.10 Binary Bitwise Operators

  1. 評估A

    生產A : A @B,其中@是 上述作品按位運算符之一,如下進行評價。

  2. 呼叫GetValue(Result(1))

  3. 評估B

  4. 呼叫GetValue(Result(3))

  5. 呼叫ToInt32(Result(2)).

  6. 呼叫ToInt32(Result(4)).

  7. 應用位運算符@Result(5)Result(6)結果是一個帶符號的32位整數

  8. 返回Result(7)

5

位運算符將它們的參數爲整數(見http://es5.github.com/#x9.5)。 大多數語言我知道不支持這種類型的轉換:

 
    $ python -c "1.0|0" 
    Traceback (most recent call last): 
     File "", line 1, in 
    TypeError: unsupported operand type(s) for |: 'float' and 'int' 

    $ ruby -e '1.0|0' 
    -e:1:in `': undefined method `|' for 1.0:Float (NoMethodError) 

    $ echo "int main(){1.0|0;}" | gcc -xc - 
    : In function ‘main’: 
    :1: error: invalid operands to binary | (have ‘double’ and ‘int’) 

+4

'S/MOST(。*?)不/強類型\ 1一般不會/'(然而,這是非常依賴語言的。) – 2012-01-28 23:59:29

2

當做floor,儘管它有可能參數轉換爲整數,這不是大多數語言會做,因爲原來的類型是浮點數。

一個更好的辦法來做到這一點,同時保留數據類型是去exponent位數爲mantissa和零剩餘位。

如果你有興趣,你可以看看浮點數IEEE spec

相關問題