JavaScript 类型转换注意事项

JavaScript 类型转换注意事项

注:部分摘自《 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.



你可能感兴趣的:(JavaScript 类型转换注意事项)