自动类型转换

请注意,数字可能会被意外转换为字符串或 NaN(非数字)。

JavaScript 是松散的类型。变量可以包含不同的数据类型,变量可以更改其数据类型:

var x = "Hello";     // typeof x is a string
x = 5;               // changes typeof x to a number

在进行数学运算时,JavaScript 可以将数字转换为字符串:

var x = 5 + 7;       // x.valueOf() is 12,  typeof x is a number
var x = 5 + "7";     // x.valueOf() is 57,  typeof x is a string
var x = "5" + 7;     // x.valueOf() is 57,  typeof x is a string
var x = 5 - 7;       // x.valueOf() is -2,  typeof x is a number
var x = 5 - "7";     // x.valueOf() is -2,  typeof x is a number
var x = "5" - 7;     // x.valueOf() is -2,  typeof x is a number
var x = 5 - "x";     // x.valueOf() is NaN, typeof x is a number

从字符串中减去字符串,不会生成错误但返回 NaN(非数字):

"Hello" - "Dolly"    // returns NaN