在js中,有四種用于檢測數(shù)據(jù)類型的方式,分別是:
typeof 用來檢測數(shù)據(jù)類型的運算符 instanceof 檢測一個實例是否屬于某個類 constructor 構(gòu)造函數(shù) Object.prototype.toString.call() 原型鏈上的Object對象的toString方法下面我們就來分別介紹一下上面四種方法的適用場景和局限性。
typeof 用來檢測數(shù)據(jù)類型的運算符
使用typeof檢測數(shù)據(jù)類型,返回值是字符串格式。能夠返回的數(shù)據(jù)類型
是:"number","string","bolean","undefined","function","object"。
<script> console.log(typeof(1)); //number console.log(typeof('hello')); //string console.log(typeof(true)); //boolean console.log(typeof(undefined)); //undefined console.log(typeof(null)); //object console.log(typeof({})); //object console.log(typeof(function() {})); //function</script>局限性:
typeof (null); //"object"。這是由于在js中,null值表示一個空對象指針,而這也正是使用typeof操作 符檢測null值時會返回"object"的原因。 不能具體的細分是數(shù)組還是正則,還是對象中其他的值,因為使用typeof檢測數(shù)據(jù)類型,對于對象數(shù)據(jù)類型的所有的值,最后返回的都是"object"instanceof 檢測某一個實例是否屬于某個類
instanceof主要用來彌補typeof不能檢測具體屬于哪個對象的局限性。
<script> let arr = [1,2,3]; let reg = //w/; console.log(arr instanceof Array); //true console.log(arr instanceof Object); //true console.log(reg instanceof RegExp); //true console.log(reg instanceof Object); //true</script>
局限性:
不能用于檢測和處理字面量方式創(chuàng)建出來的基本數(shù)據(jù)類型值,即原始數(shù)據(jù)類型 instanceof的特性:只要在當前實例的原型鏈上的對象,我們用其檢測出來都為true 在類的原型繼承中,我們最后檢測出來的結(jié)果未必正確constructor 構(gòu)造函數(shù)
是函數(shù)原型上的屬性,該屬性指向的是構(gòu)造函數(shù)本身。
作用和instsnceof非常相似,與instanceof不同的是,不僅可以處理引用數(shù)據(jù)類型,還可以處理原始數(shù)據(jù)類型。
<script> let num = 12; let obj = {}; console.log(num.constructor == Number);//true console.log(obj.constructor == Object);//true</script>但是要注意一點的是,當直接用(對象字面量或原始數(shù)據(jù)).constructor時,最好加上()。為了便于理解,我們來看一個例子。
<script> 1.constructor === Number; //報錯,Invalid or unexceped token (1).constructor === Number; //true {}.constructor === Number; //報錯,Invalid or unexceped token ({}).constructor === Number; //true</script>這主要是由于js內(nèi)部解析方式造成的,js會把1.constructor解析成小數(shù),這顯然是不合理的,小數(shù)點后應該是數(shù)字,因此就會引發(fā)報錯。js會把{}解析成語句塊來執(zhí)行,這時后面出現(xiàn)一個小數(shù)點顯然也是不合理的,因此也會報錯。為了解決這個問題,我們可以為表達式加上()使js能夠正確解析。
|
新聞熱點
疑難解答
圖片精選