类型转换

类型转换是将一个值从一种类型更改为另一个类型的过程。 例如,可以将字符串“1234”转换为一个数字。 而且,可以将任意类型的数据转换为 String 类型。 某些类型转换永远不会成功。 例如,Date 对象不能转换为 ActiveXObject 对象。

类型转换有可能扩大,也有可能收缩:扩大转换永远不会溢出,并且总是成功的;而收缩转换必然伴有信息的丢失,并有可能失败。

两种转换类型都可以是显式(使用数据类型标识符)或隐式(不使用数据类型标识符)的。 有效的显式转换即使会导致信息的丢失,也始终是成功的。 而隐式转换只有在转换过程不丢失数据的情况下才能成功;否则,它们就会失败并生成编译或运行时错误。

当原始数据类型在目标转换类型中没有明显的对应类型时,就会发生丢失数据的转换。 例如,字符串“Fred”不能转换为一个数字。 在这些情况下,类型转换函数将返回一个默认值。 对于 Number 类型,默认值为 NaN;对于 int 类型,默认值为数字 0。

某些类型的转换(比如从字符串转换为数字)非常耗时。 程序使用的转换越少,效率就越高。

隐式转换

大多数类型转换(比如给变量赋值)会自动发生。 变量的数据类型决定了表达式转换的目标数据类型。

本示例说明如何在 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 数据之间相互转换。 另外,转换对于某些值是不可能的,因为对于要转换的值没有敏感的值。 例如,当尝试将双精度值 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 属性

概念

type 批注

其他资源

JScript 数据类型