JavaScript類型判斷的四種方法

JavaScript數(shù)據(jù)類型

JavaScript有八種內(nèi)置類型,除對(duì)象外,其他統(tǒng)稱為“基本類型”。

  • 空值(null)

  • 未定義(undefined)

  • 布爾值(boolean)

  • 數(shù)字(number)

  • 字符串(string)

  • 對(duì)象 (object)

  • 符號(hào)(symbol, ES6中新增)

  • 大整數(shù)(BigInt, ES2020 引入)

Symbol: 是ES6中引入的一種原始數(shù)據(jù)類型,表示獨(dú)一無二的值。

BigInt:是 ES2020 引入的一種新的數(shù)據(jù)類型,用來解決 JavaScript中數(shù)字只能到 53 個(gè)二進(jìn)制位(JavaScript 所有數(shù)字都保存成 64 位浮點(diǎn)數(shù),大于這個(gè)范圍的整數(shù),無法精確表示的問題。具體可查看:新數(shù)據(jù)類型 — BigInt

一、typeof

typeof是一個(gè)操作符而不是函數(shù),其右側(cè)跟一個(gè)一元表達(dá)式,并返回這個(gè)表達(dá)式的數(shù)據(jù)類型。返回的結(jié)果用該類型的字符串(全小寫字母)形式表示,包括以下 8 種:number、boolean、symbol、string、object、undefined、function 、bigInt等。

typeof原理是不同的對(duì)象在底層都表示為二進(jìn)制,在Javascript中二進(jìn)制前(低)三位存儲(chǔ)其類型信息。

  • 000: 對(duì)象

  • 010: 浮點(diǎn)數(shù)

  • 100:字符串

  • 110:布爾

  • 1:整數(shù)

console.log(typeof undefined) // undefind
console.log(typeof null)      // object
console.log(typeof true)      // boolean
console.log(typeof 43)        // number
console.log(typeof '21')      // string
console.log(typeof {a:1})     // object
console.log(typeof Symbol())  // symbol
console.log(typeof 123n)      // bigint
function a() {}
console.log(typeof a)         // function
var date = new Date()
var error = new Error()
console.log(typeof date)      // object
console.log(typeof error)     // object

二、instanceof

instanceof 是用來判斷 A 是否為 B 的實(shí)例,表達(dá)式為:A instanceof B,如果 A 是 B 的實(shí)例,則返回 true,否則返回 false。 在這里需要特別注意的是:instanceof 檢測(cè)的是原型

通俗一些講,instanceof 用來比較一個(gè)對(duì)象是否為某一個(gè)構(gòu)造函數(shù)的實(shí)例。注意,instanceof可以準(zhǔn)確的判斷復(fù)雜數(shù)據(jù)類型,但是不能正確判斷基本數(shù)據(jù)類型

console.log(12 instanceof Number)  // false
console.log('22' instanceof String)  // false
console.log(true instanceof Boolean) // false
console.log(null instanceof Object) // false
console.log(undefined instanceof Object) // false

console.log([] instanceof Array)   // true
console.log({a: 1} instanceof Object) // true
console.log(json instanceof Object) // true
function a() {}
console.log(a instanceof Function)  // true
console.log(new Date() instanceof Date)  //true
console.log(reg instanceof RegExp) //true
console.log(error instanceof Error) // true

三、Object.prototype.toString.call()

toString() 是 Object 的原型方法,調(diào)用該方法,默認(rèn)返回當(dāng)前對(duì)象的 [[Class]] 。這是一個(gè)內(nèi)部屬性,其格式為 [object Xxx] ,其中 Xxx 就是對(duì)象的類型。

對(duì)于 Object 對(duì)象,直接調(diào)用 toString() 就能返回 [object Object] 。而對(duì)于其他對(duì)象,則需要通過 call / apply 來調(diào)用才能返回正確的類型信息。

console.log(Object.prototype.toString.call(1))          // [object Number]
console.log(Object.prototype.toString.call(1n))         // [object BigInt]
console.log(Object.prototype.toString.call('123'))      // [object String]
console.log(Object.prototype.toString.call(true))       // [object Boolean]
console.log(Object.prototype.toString.call(undefined))  // [object Undefined]
console.log(Object.prototype.toString.call(null))       // [object Null]
console.log(Object.prototype.toString.call({}))         // [object Object]
console.log(Object.prototype.toString.call([]))         // [object Array]
console.log(Object.prototype.toString.call(function a() {}))  // [object Function]
console.log(Object.prototype.toString.call(Symbol()))         // [object Symbol]
console.log(Object.prototype.toString.call(Math))             // [object Math]
console.log(Object.prototype.toString.call(JSON))             // [object JSON]
console.log(Object.prototype.toString.call(new Date()))       // [object Date]
console.log(Object.prototype.toString.call(new RegExp()))     // [object RegExp]
console.log(Object.prototype.toString.call(new Error))        // [object Error]
console.log(Object.prototype.toString.call(window)            // [object Window]
console.log(Object.prototype.toString.call(document)          // [object HTMLDocument]

使用該方法我們可以封裝一個(gè)isType方法來對(duì)類型進(jìn)行判斷

let isType = (type, obj) => {
    return Object.prototype.toString.call(obj) === `[object ${type}]`
}
console.log(isType('Number', 12))   // true
console.log(isType('Number', '12')) // false

或者

let type = function(o) {
    let s = Object.prototype.toString.call(o);
    return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
console.log(type(12)) // number
console.log(type('12')) // string
console.log(type({})) // object
console.log(type([])) // array

四、constructor

constructor屬性,可以得知某個(gè)實(shí)例對(duì)象,到底是哪一個(gè)構(gòu)造函數(shù)產(chǎn)生的。

constructor屬性表示原型對(duì)象與構(gòu)造函數(shù)之間的關(guān)聯(lián)關(guān)系,如果修改了原型對(duì)象,一般會(huì)同時(shí)修改constructor屬性,防止引用的時(shí)候出錯(cuò)。所以,修改原型對(duì)象時(shí),一般要同時(shí)修改constructor屬性的指向。

console.log('22'.constructor === String)             // true
console.log(true.constructor === Boolean)            // true
console.log([].constructor === Array)                // true
console.log(document.constructor === HTMLDocument)   // true
console.log(window.constructor === Window)           // true
console.log(new Number(22).constructor === Number)   // true
console.log(new Function().constructor === Function) // true
console.log((new Date()).constructor === Date)       // true
console.log(new RegExp().constructor === RegExp)     // true
console.log(new Error().constructor === Error)       // true

注意:

1、null 和 undefined 是無效的對(duì)象,因此是不會(huì)有 constructor 存在的,這兩種類型的數(shù)據(jù)需要通過其他方式來判斷。

2、函數(shù)的 constructor 是不穩(wěn)定的,這個(gè)主要體現(xiàn)在自定義對(duì)象上,當(dāng)開發(fā)者重寫 prototype 后,原有的 constructor 引用會(huì)丟失,constructor 會(huì)默認(rèn)為 Object

文章每周持續(xù)更新,可以微信搜索「 前端大集錦 」第一時(shí)間閱讀,回復(fù)【視頻】【書籍】領(lǐng)取200G視頻資料和30本PDF書籍資料

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容