JavaScript 類型轉(zhuǎn)換
Number() 轉(zhuǎn)換為數(shù)字带欢, String() 轉(zhuǎn)換為字符串, Boolean() 轉(zhuǎn)化為布爾值烤惊。
JavaScript 數(shù)據(jù)類型
在 JavaScript 中有 5 種不同的數(shù)據(jù)類型:
string
number
boolean
object
function
3 種對(duì)象類型:
Object
Date
Array
2 個(gè)不包含任何值的數(shù)據(jù)類型:
null
undefined
typeof 操作符
你可以使用 typeof 操作符來(lái)查看 JavaScript 變量的數(shù)據(jù)類型乔煞。
實(shí)例
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 沒(méi)有聲明)typeof null // 返回 object
嘗試一下 ?
請(qǐng)注意:
NaN 的數(shù)據(jù)類型是 number
數(shù)組(Array)的數(shù)據(jù)類型是 object
日期(Date)的數(shù)據(jù)類型為 object
null 的數(shù)據(jù)類型是 object
未定義變量的數(shù)據(jù)類型為 undefined
如果對(duì)象是 JavaScript Array 或 JavaScript Date ,我們就無(wú)法通過(guò) typeof 來(lái)判斷他們的類型柒室,因?yàn)槎际?返回 Object渡贾。
constructor 屬性
constructor 屬性返回所有 JavaScript 變量的構(gòu)造函數(shù)。
實(shí)例
"John".constructor // 返回函數(shù) String() { [native code] }(3.14).constructor // 返回函數(shù) Number() { [native code] }false.constructor // 返回函數(shù) Boolean() { [native code] }[1,2,3,4].constructor // 返回函數(shù) Array() { [native code] }{name:'John', age:34}.constructor // 返回函數(shù) Object() { [native code] } new Date().constructor // 返回函數(shù) Date() { [native code] }function () {}.constructor // 返回函數(shù) Function(){ [native code] }
節(jié)選自:http://www.runoob.com/js/js-type-conversion.html