JavaScript 類型轉換
Number() 轉換為數字, String() 轉換為字符串, Boolean() 轉化為布爾值。
JavaScript 數據類型
在 JavaScript 中有 5 種不同的數據類型:
string
number
boolean
object
function
3 種對象類型:
Object
Date
Array
2 個不包含任何值的數據類型:
null
undefined
typeof 操作符
你可以使用 typeof 操作符來查看 JavaScript 變量的數據類型。
實例
typeof "John" // 返回 stringtypeof 3.14 // 返回 numbertypeof NaN // 返回 numbertypeof false // 返回 booleantypeof [1,2,3,4] // 返回 objecttypeof {name:'John', age:34} // 返回 objecttypeof new Date() // 返回 objecttypeof function () {} // 返回 functiontypeof myCar // 返回 undefined (如果 myCar 沒有聲明)typeof null // 返回 object
嘗試一下 ?
請注意:
NaN 的數據類型是 number
數組(Array)的數據類型是 object
日期(Date)的數據類型為 object
null 的數據類型是 object
未定義變量的數據類型為 undefined
如果對象是 JavaScript Array 或 JavaScript Date ,我們就無法通過 typeof 來判斷他們的類型,因為都是 返回 Object。
constructor 屬性
constructor 屬性返回所有 JavaScript 變量的構造函數。
實例
"John".constructor // 返回函數 String() { [native code] }(3.14).constructor // 返回函數 Number() { [native code] }false.constructor // 返回函數 Boolean() { [native code] }[1,2,3,4].constructor // 返回函數 Array() { [native code] }{name:'John', age:34}.constructor // 返回函數 Object() { [native code] } new Date().constructor // 返回函數 Date() { [native code] }function () {}.constructor // 返回函數 Function(){ [native code] }
節選自:http://www.runoob.com/js/js-type-conversion.html