JS中的四種資料型別判斷方法
目錄
- 1、typeof
- 2、instanceof
- 3、constructor
- 4、toString()
本文總結了四種判斷方法:
1、typeof
typeof
是一個運算子,其有兩種使用方式:(1)typeof
(表示式); (2)typeof
變數名;返回值是一個字串,用來說明變數的資料型別;所以可以用此來判斷number
,string
,object
,boolean
,function
,undefined
,symbol
這七種型別,每種情況返回的內容如下表所示:
// 字串 console.log(typeof('lili')); // string // 數字 console.log(typeof(1));// number // 布林值 console.log(typeof(true)); // boolean // undefined console.log(typeof(undefined)); // undefined // 物件 console.log(typeof({})); // object // 陣列 console.log(typeof([])); // object // null console.log(typeof(null)); // object // 函式 console.log(typeof(() => {})); // function // Symbol值 console.log(typeof(Symbol())); // symbol
2、instanceof
instanceof
運算子用於檢測建構函式的 prototype
屬性是否出現在某個例項物件的原型鏈上,返回值為布林值,用於指示一個變數是否屬於某個物件的例項。其語法如下所示:
object instanceof constructor
const arr = [1,2]; // 判斷Object的prototype有沒有在陣列的原型鏈上 console.log(arr instanceof Object); // true // 陣列arr的原型 const proto1 = Object.getPrototypeOf(arr); console.log(proto1); // [] // 陣列arr的原型的原型 const proto2 = Object.getPrototypeOf(proto1); console.log(proto2); // [] // Object的prototype console.log(Object.prototype); // 判斷arr的原型是否與Object的prototype相等 console.log(proto1 === Object.prototype); // false // 判斷arr的原型的原型是否與Object的prototype相等 console.log(proto2 === Object.prototype); // true
3、constructor
該種判斷方式其實涉及到原型、建構函式和例項之間的關係,更深層次的講解將放到後面的內容,下面只需要簡單瞭解一下這三者關係即可。
在定義一個函式(建構函式)的時候,引擎會為其新增prototype
原型,原型上有其對應的constructor
屬性指向該建構函式,從而原型和建構函式之間互相知道對方。當建構函式例項化的時候,會產生對應的例項,其例項可以訪問對應原型上的constructor
屬性,這樣該例項就可以瞭解到通過誰產生了自己,這樣就可以在新物件產生之後瞭解其資料型別。
const val1 = 1; console.log(val1.constructor); // [Function: Number] const val2 = 'abc'; console.log(val2.constructor); // [Function: String] const val3 = true; console.log(val3.constructor); // [Function: Boolean]
雖然該方法可以判斷其資料型別,但存在兩個缺點:
null
和undefined
是無效的物件,因此是不會有constructor
存在的,這兩種型別的資料需要通過其他方式來判斷。- 函式的
constructor
是不穩定的,這個主要體現在自定義物件上,當開發者重寫prototype
後,原有的constructor
引用會丟失,constructor
會預設為Object
4、toString()
toString()
是 Object
的原型方法,呼叫該方法,預設返回當前物件的 [[Class]]
。這是一個內部屬性,其格式為[object Xxx]
,其中 Xxx 就是物件的型別。所以利用Object.prototype.toString()
方法可以對變數的型別進行比較準確的判斷。
該型別針對不同不同變數的型別返回的結果如下所示:
利用該方法很容易構建一個鑑型函式,程式碼如下所示:
function type(target) { const ret = typeof(target); const template = { "[object Array]": "array","[object Object]":"object","[object Number]":"number - object","[object Boolean]":"boolean - object","[object String]":'string-object' } if(target === null) { return 'null'; } else if(ret == "object"){ const str = Object.prototype.toString.call(target); return template[str]; BmhwWA} else{ return ret; } }
console.log(type({})); // object console.log(type(123)); // number console.log(type('123')); // string
到此這篇關於JS中的四種資料型別判斷方法的文章就介紹到這了,更多相關JS中的資料型別判斷方法內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!