1七芭、 typeof
typeof
操作符返回一個字符串秦踪,表示未經計算的操作數(shù)的類型懂鸵。
語法:typeof operand
看下面例子:
> typeof 1
output: "number"
> typeof '1'
output: "string"
> typeof true
output: "boolean"
> typeof null
output: "object"
> typeof undefined
output: "undefined"
> typeof []
output: "object"
> typeof function () {}
output: "function" // 一些瀏覽器會是 object
> typeof {}
output: "object"
> typeof Symbol()
output: "symbol"
由上可看卒煞,typeof很好用痪宰,但有缺陷,像null
畔裕、數(shù)組
都被判定為object
衣撬。
null
會被判斷為object
跟JavaScript開始的設計有關具體解釋看這
那么,為什么數(shù)組
被判定為object
呢柴钻?其實與數(shù)據(jù)背景有關:
JavaScript中有兩種數(shù)據(jù)類型:
1淮韭、原始數(shù)據(jù)類型:包括null,undefind贴届,String靠粪,Boolean,Number和Object毫蚓。
2占键、派生數(shù)據(jù)類型/特殊對象:包括Function,Array和RegExp元潘。這些都是JavaScript中的“Object”派生而來的畔乙。
2、instanceof
instanceof
運算符用于檢測構造函數(shù)的prototype
屬性是否出現(xiàn)在某個實例對象的原型鏈
上翩概。即instanceof
是用于判斷引用類型
屬于哪個構造函數(shù)
的
語法:object instanceof constructor
留意語法中的 constructor
看下面例子:
> [] instanceof Array
output: true
> [] instanceof Object
output: true
> ({}) instanceof Object //一定要加原括號牲距,不然 {} 被認為是語句會報錯
output: true
> (function () {} ) instanceof Function
output: true
> (function () {} ) instanceof Object
output: true
> /\d/ instanceof RegExp
output: true
> /\d/ instanceof Object
output: true
// 特殊的
> class a {}
> class b extends a {
}
> const oB = new b()
> a instanceof Function
output: true
> b instanceof Function
output: true
> oB instanceof b
output: true
> oB instanceof a
output: true
> oB instanceof Object
output: true
3返咱、封裝一個函數(shù)判斷數(shù)據(jù)類型
每個對象都有一個
toString
方法,當該對象被表示為一個文本值時牍鞠,或者一個對象以預期的字符串方式引用時自動調用咖摹。如果此方法在自定義對象中未被覆蓋,toString()
返回 "[object type]
"难述,其中 type 是對象的類型
封裝(返回結果根據(jù)自己決定是否返回小寫萤晴,跟.toLowerCase()
來實現(xiàn)),以下結果首字母大寫:
const _toString = Object.prototype.toString
function type (param) {
const str = _toString.call(param)
return str.slice(8, str.length -1)
}
應用:
> type(1)
output: "Number"
> type('1')
output: "String"
> type(null)
output: "Null"
> type(undefined)
output: "Undefined"
> type(true)
output: "Boolean"
> type(NaN)
output: "Number"
> type([])
output: "Array"
> type(Symbol())
output: "Symbol"
> type(function () {})
output: "Function"
> type(class a {})
output: "Function"
> type (new Set())
output: "Set"
> type (new Map())
output: "Map"
4胁后、其他
- 判斷數(shù)組
Array.isArray(obj) 方法
參數(shù):obj
為需要檢測的值店读。
返回值:如果值是Array
,則為true
; 否則為false