类型转换总结(JavaScript: The Definitive Guide学习摘要3)

Section 3.12. Type Conversion Summary

|

—|—

Value

|

Context in which value is used

—|—

|

String

|

Number

|

Boolean

|

Object

3.12. Type Conversion Summary

As each datatype has been described in the previous sections, I’ve discussed
how values of each type convert into values of other types. The basic rule is
that when a value of one type is used in a context that requires a value of
some other type, JavaScript automatically attempts to convert the value as
needed. So, for example, if a number is used in a Boolean context, it is
converted to a boolean. If an object is used in a string context, it is
converted to a string. If a string is used in a numeric context, JavaScript
attempts to convert it to a number. Table 3-3 summarizes each of these
conversions and shows the conversion that is performed when a particular type
of value is used in a particular context.

Table 3-3. Automatic datatype conversions

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

|
—|—