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屬性
適合自定義對象,也可以用來檢測原生類型,在不同iframe和window之間檢測失效
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)置對象和基元類型,遇到null和undefined失效(IE6/7/8等返回[object Object])
[object class]是對象的類屬性,用以表達(dá)對象的類型信息
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對象
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)證
- 為了簡化代碼,先使用instanceof來驗(yàn)證部分類型,剩下的就可以直接使用typeof來驗(yàn)證類型