Share via


型別轉換

更新:2007 年 11 月

型別轉換是將值從一種型別變更為另一種型別的過程。例如,您可以將 "1234" 字串轉換為一個數字。您還可以將任何型別的資料,轉換為 String 型別。有些型別永遠無法轉換成功。例如,Date 物件無法轉換為 ActiveXObject 物件。

型別轉換可以是「擴展」或「縮小」:擴展轉換從不會溢位,而且一定成功,但是縮小轉換卻可能造成資訊遺失,甚至失敗。

兩種轉換型別可能是明確 (利用資料型別識別項) 或隱含 (無資料型別識別項)。有效的明確轉換即使會造成資訊遺失,也能轉換成功。隱含轉換只在處理序不遺失資料時才會成功,否則會失敗並且產生編譯或執行階段錯誤。

原始資料型別的目標轉換型別中沒有明顯的類比方式時,就會發生遺失轉換。例如,字串 "Fred" 不能轉換為一個數字。在這些情況下,會從型別轉換函式傳回預設值。若是 Number 型別,預設值為 NaN;int 型別的預設值則是數字零。

有些轉換類型十分耗費時間,例如從字串轉換為數字。程式使用的轉換愈少,效率愈高。

隱含轉換

大部分的型別轉換,例如指派變數值,都會自動發生。變數的資料型別,決定運算式轉換的目標資料型別。

這個範例示範 int 值、String 值和 double 值之間,如何隱含轉換資料。

var i : int;
var d : double;
var s : String;
i = 5;
s = i;  // Widening: the int value 5 coverted to the String "5".
d = i;  // Widening: the int value 5 coverted to the double 5.
s = d;  // Widening: the double value 5 coverted to the String "5".
i = d;  // Narrowing: the double value 5 coverted to the int 5.
i = s;  // Narrowing: the String value "5" coverted to the int 5.
d = s;  // Narrowing: the String value "5" coverted to the double 5.

當編譯這個程式碼時,可能會有編譯時期警告,陳述縮小轉換可能會失敗或進行緩慢。

如果轉換時會遺失資訊,隱含的縮小轉換可能無法運作。例如,下列幾行就無法運作。

var i : int;
var f : float;
var s : String;
f = 3.14;
i = f;  // Run-time error. The number 3.14 cannot be represented with an int.
s = "apple";
i = s;  // Run-time error. The string "apple" cannot be converted to an int.

明確轉換

若要將運算式明確轉換為特定的資料型別,請使用資料型別識別項,後面加上要進行轉換的運算式 (以括號括住)。明確轉換需要撰寫比隱含轉換多的程式碼,但是您更能掌握結果。而且,明確轉換可以處理轉換損失。

這個範例示範 int 值、String 值和 double 值之間,如何明確轉換資料。

var i : int;
var d : double;
var s : String;
i = 5;
s = String(i);  // Widening: the int value 5 coverted to the String "5".
d = double(i);  // Widening: the int value 5 coverted to the double 5.
s = String(d);  // Widening: the double value 5 coverted to the String "5".
i = int(d);     // Narrowing: the double value 5 coverted to the int 5.
i = int(s);     // Narrowing: the String value "5" coverted to the int 5.
d = double(s);  // Narrowing: the String value "5" coverted to the double 5.

即使轉換時會遺失資訊,明確的縮小轉換還是能運作。不相容的資料型別之間,不能使用明確轉換。例如,Date 和 RegExp 資料之間不能轉換。此外,有些值因為沒有合理的轉換值,所以不能轉換。例如,如果您試圖將 double 值 NaN 明確轉換為 decimal,就會發生錯誤。這是因為 NaN 沒有可識別的自然 decimal 值。

在此範例中,含小數部分的數字被轉換為一個整數,而字串則被轉換為一個整數。

var i : int;
var d : double;
var s : String;
d = 3.14;
i = int(d);
print(i);
s = "apple";
i = int(s);
print(i);

輸出為

3
0

明確轉換的行為同時取決於原始和目標資料型別。

請參閱

概念

型別附註

參考

undefined 屬性

其他資源

JScript 資料型別