注:部分摘自《
JavaScript: The Definitive Guide, 5th Edition》
字符型轉換為數值型可以使用下列方法
parseInt(stringVar); //parseInt還可以指定二進制、八進制、或16進制
parseFloat(stringVar);
Number(stringVar);
for example:
parseInt("ff") //will throw a error
parseInt("ff", 16) == parseInt("0xff") // return 255
parseInt("77") //return 77
parseInt("077") == parseInt("77", 8) // return 63
注:加"0"或"0x"前綴會自動檢測并轉換為相應的數制所表示的值
If parseInt( ) or parseFloat( ) cannot convert the specified
string to a number, it returns NaN
數值型轉換為字符型
numberVar + "";
numberVar.toString(); //可以指定二進制、八進制、或16進制
String(numberVar);
other useful method
var n = 123456.789;
n.toFixed(0); // "123457"
n.toFixed(2); // "123456.79"
n.toExponential(1); // "1.2e+5"
n.toExponential(3); // "1.235e+5"
n.toPrecision(4); // "1.235e+5"
n.toPrecision(7); // "123456.8"
其實還有一種方法就是使用new操作符,如
new String(numberVar);
new Numer(stringVar);
但是這種方法返回的結果是object類型,而不是原始數據類型,大家可以酌情使用。
另外,在相等判斷時使用' == '會自動轉型(具體轉換情況請參考其他資料),如果想精確判斷請使用' === '。
如 1 == '1' //return true
1 === '1' //return false
1 == new Number(1) //return true
1 === new Number(1) //return false
數值連接等相關操作
"21" + "2" == "21" + 2 //return 212
2 + "21" //return 221
"21" * "2" == "21" * 2 == 2 * "21" //return 42
"21" / "3" == "21" / 3 == 21 / "3" //return 7
"21" - "2" == "21" - 2 == 21 - "2" == 21 - " 2 " //return 19
正如和Java中一樣,new Number(3) == new Number(3)返回false,同理推廣到其他類型,new操作符總是建立一個新對象,
而==只是比較其引用,并不比較對象本身,所以兩個new的對象的引用總是不同的。所以在通常的邏輯判斷中(如if或while等),
最好避免使用Primitive Datatype Wrapper,而直接使用Primitive Datatype。
From Wrapper to Primitive, for example:
new Number(3).valueOf()
new String("str").valueOf()
new Date().valueOf() //convert a Date to millisecond representation
[any other object].valueOf() //The primitive value associated with the
object,
if any. If there is no value associated with
object, returns the
object itself.
Finally, note that any number, string, or boolean value can be
converted to its corresponding wrapper object with the Object( )
function:
var number_wrapper = Object(3);
Automatic datatype conversions
Value
|
Context in which value is used
|
|
String
|
Number
|
Boolean
|
Object
|
Undefined value
|
"undefined"
|
NaN
|
false
|
Error
|
null
|
"null"
|
0
|
false
|
Error
|
Nonempty string
|
As is
|
Numeric value of string or NaN
|
TRue
|
String object
|
Empty string
|
As is
|
0
|
false
|
String object
|
0
|
"0"
|
As is
|
false
|
Number object
|
NaN
|
"NaN"
|
As is
|
false
|
Number object
|
Infinity
|
"Infinity"
|
As is
|
true
|
Number object
|
Negative infinity
|
"-Infinity"
|
As is
|
TRue
|
Number object
|
Any other number
|
String value of number
|
As is
|
true
|
Number object
|
true
|
"true"
|
1
|
As is
|
Boolean object
|
false
|
"false"
|
0
|
As is
|
Boolean object
|
Object
|
toString( )
|
valueOf( ), toString( ), or
NaN
|
true
|
As is
|
利用上面的表,我們可以知道if ("") 、if (0)、if (undefined)、if (null)、if (NaN),這些if語句的條件都為false.