本文翻譯自:What is the difference between parseInt() and Number()?
將字符串轉換爲數字時, parseInt()
和Number()
行爲如何不同?
#1樓
參考:https://stackoom.com/question/HA86/parseInt-和Number-有什麼區別
#2樓
If you are looking for performance then probably best results you'll get with bitwise right shift "10">>0
. 如果您正在尋找性能,那麼最好按位右移"10">>0
獲得最佳結果。 Also multiply ( "10" * 1
) or not not ( ~~"10"
). 還要乘以( "10" * 1
)或不乘( ~~"10"
)。 All of them are much faster of Number
and parseInt
. 所有這些parseInt
Number
和parseInt
快得多。 They even have "feature" returning 0 for not number argument. 他們甚至具有“功能”,而不是數字參數返回0。 Here are Performance tests . 這是性能測試 。
#3樓
I found two links of performance compare among several ways of converting string
to int
. 我發現在將string
轉換爲int
幾種方法中,比較了性能的兩個鏈接。
parseInt(str,10)
parseFloat(str)
str << 0
+str
str*1
str-0
Number(str)
http://jsben.ch/#/zGJHM http://jsben.ch/#/zGJHM
http://phrogz.net/js/string_to_number.html http://phrogz.net/js/string_to_number.html
#4樓
我一直使用parseInt,但是要注意前導零會迫使它進入八進制模式。
#5樓
typeof parseInt("123") => number
typeof Number("123") => number
typeof new Number("123") => object (Number primitive wrapper object)
first two will give you better performance as it returns a primitive instead of an object. 前兩個會返回原始值而不是對象,因此會提高性能。
#6樓
Well, they are semantically different , the Number
constructor called as a function performs type conversion and parseInt
performs parsing , eg: 嗯,它們在語義上是不同的 , 稱爲函數的Number
構造函數執行類型轉換 , parseInt
執行解析 ,例如:
// parsing:
parseInt("20px"); // 20
parseInt("10100", 2); // 20
parseInt("2e1"); // 2
// type conversion
Number("20px"); // NaN
Number("2e1"); // 20, exponential notation
Keep in mind that if parseInt
detects a leading zero on the string, it will parse the number in octal base, this has changed on ECMAScript 5, the new version of the standard, but it will take a long time to get in browser implementations (it's an incompatibility with ECMAScript 3), also parseInt
will ignore trailing characters that don't correspond with any digit of the currently used base. 請記住,如果parseInt
在字符串上檢測到前導零,則它將以八進制爲基礎解析數字,這在標準的新版本ECMAScript 5中已更改,但是要花很長時間才能進入瀏覽器實現( (與ECMAScript 3不兼容), parseInt
也會忽略與當前使用的基數不匹配的尾隨字符。
The Number
constructor doesn't detect octals: Number
構造函數不檢測八進制:
Number("010"); // 10
parseInt("010"); // 8, implicit octal
parseInt("010", 10); // 10, decimal radix used
But it can handle numbers in hexadecimal notation, just like parseInt
: 但是它可以以十六進制表示法處理數字,就像parseInt
一樣:
Number("0xF"); // 15
parseInt("0xF"); //15
In addition, a widely used construct to perform Numeric type conversion, is the Unary +
Operator (p. 72) , it is equivalent to using the Number
constructor as a function: 另外,用於執行數值類型轉換的一種廣泛使用的構造是Unary +
運算符(p。72) ,它等效於將Number
構造函數用作函數:
+"2e1"; // 20
+"0xF"; // 15
+"010"; // 10