typeof
適合基本類型和函數(shù)類型窍帝,遇到null失效
typeof 123 // 'number'
typeof ‘string’ // 'string'
typeof false // 'boolean'
typeof undefined // 'undefined'
typeof null // 'object'
typeof function(){} // 'function'
instanceof
判斷左邊的原型鏈上是否有右邊構(gòu)造函數(shù)的prototype屬性
適合自定義對(duì)象,也可以用來檢測(cè)原生類型,在不同iframe和window之間檢測(cè)失效
function Person() {}
function Student() {}
var person = new Person
Student.prototype = new Person
var yz = new Student
person instanceof Person // true
yz instanceof Student // true
yz instanceof Person // true
Object.prototype.toString.apply()
通過{}.toString()拿到,適合內(nèi)置對(duì)象和基元類型,遇到null和undefined失效(IE6/7/8等返回[object Object])
[object class]是對(duì)象的類屬性,用以表達(dá)對(duì)象的類型信息
Object.prototype.toString.apply(new Array) // '[object Array]'
Object.prototype.toString.apply(new Date) // '[object Date]'
Object.prototype.toString.apply(new RegExp) // '[object Regexp]'
Object.prototype.toString.apply(function(){}) // '[object Function]'
Object.prototype.toString.apply(false) // '[object Boolean]'
Object.prototype.toString.apply('string') // '[object String]'
Object.prototype.toString.apply(1) // '[object Number]'
Object.prototype.toString.apply(undefined) // [object Undefined]'
Object.prototype.toString.apply(null) // '[object Null]'
Object.prototype.toString.apply(window) // '[object Window]'
判斷各種類型
// 代碼出自慕課網(wǎng)《JavaScript深入淺出》1-6節(jié)
// 判斷String纫谅、Number、Boolean溅固、undefined付秕、null、函數(shù)侍郭、日期询吴、window對(duì)象
function typeof(el) {
var result
if (el === null) {
result = 'null'
} else if (el instanceof Array) {
result = 'array'
} else if (el instanceof Date) {
result = 'date'
} else if (el === window) {
result = 'window'
} else {
result = typeof el
}
return result
}
代碼分析:
- 使用typeof運(yùn)算符可以確定出number、string亮元、boolean猛计、function、undefined爆捞、object這六種
- 但object中還包括了Array奉瘤、RegExp、Object煮甥、Date盗温、Number、Boolean成肘、String這幾種構(gòu)造函數(shù)
- 所以可以使用instanceof運(yùn)算符來排除相應(yīng)的類型
- null和window使用全等運(yùn)算符進(jìn)行驗(yàn)證
- 為了簡(jiǎn)化代碼肌访,先使用instanceof來驗(yàn)證部分類型,剩下的就可以直接使用typeof來驗(yàn)證類型