自動型別轉換

請注意,數字可能會被意外轉換為字串或 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