Javascript 用雙波浪號 ~~ 來 屌炸天 轉型整數前請三思
tl;dr
曾幾何時看到別人 JS 寫雙波浪號 來把 string 轉型成 number 而且是整數
http://qa.helplib.com/84467
例如 ~~'123.456' = 123
其實效果跟 Math.floor('123.456') 一樣
某些瀏覽器可能用雙波浪寫法會快上一些
https://jsperf.com/tilde-vs-floor
然而 Number.MAX_SAFE_INTEGER 是 9007199254740991
照理來說 只要不超過這個數字 應該就沒事吧
事實上 只有 -2147483648 ~ 2147483648 範圍的值有作用
Bitwise operators treat their operands as a sequence of 32 bits (zeroes and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable through a 32bit signed number.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
簡單來說只要值超過 2147483648 就 GG 啦
我已經不知多少專案用了這個寫法 祈禱他們都只會小於 2147483648
如果有不幸 我相信接手的人都足夠機智 可以突破盲腸
tl;dr
曾幾何時看到別人 JS 寫雙波浪號 來把 string 轉型成 number 而且是整數
http://qa.helplib.com/84467
例如 ~~'123.456' = 123
其實效果跟 Math.floor('123.456') 一樣
某些瀏覽器可能用雙波浪寫法會快上一些
https://jsperf.com/tilde-vs-floor
然而 Number.MAX_SAFE_INTEGER 是 9007199254740991
照理來說 只要不超過這個數字 應該就沒事吧
事實上 只有 -2147483648 ~ 2147483648 範圍的值有作用
Bitwise operators treat their operands as a sequence of 32 bits (zeroes and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable through a 32bit signed number.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
簡單來說只要值超過 2147483648 就 GG 啦
我已經不知多少專案用了這個寫法 祈禱他們都只會小於 2147483648
如果有不幸 我相信接手的人都足夠機智 可以突破盲腸