JavaScript精確判斷物件型別——Object.prototype.toString
阿新 • • 發佈:2018-12-19
面試中經常會問到js的資料型別有哪些,以及如何判斷資料型別的問題,對於基本資料型別undefined,string,boolean,number,symbol使用最常用的typeof即可判斷,但是對於null,array,{}使用typeof就會統一返回object字串,這樣就不能準確的判斷。怎麼解決的呢,來看下面:
首先使用typeof來判斷基本的資料型別:
//基本資料型別:number、string、boolean、null、undefined //引用資料型別:object(Array、Data、RegExp、function) alert(typeof 1); //number; alert(typeof true); //boolean; alert(typeof undefined); //undefined; alert(typeof "hello world") //string; alert(typeof {}); //object; alert(typeof []); //object; alert(typeof null); //object, null是一個空物件; alert(typeof function(){}); //function;
如上:對於null(空物件)、陣列、{}(物件)使用typeof判斷資料型別,都會統一返回“object”字串;
Object.prototype.toString方法精確判斷
其過程簡單說來就是: 1. 獲取物件的類名(物件型別)。 2. 然後將[object、獲取的物件型別的名、]組合為字串 3. 返回字串 “[object Array]” 。
[[Class]]是一個內部屬性,所有的物件(原生物件和宿主物件)都擁有該屬性.在規範中,[[Class]]是這麼定義的: 內部屬性,[[Class]] 一個字串值,表明了該物件的型別。
由於 JavaScript 中一切都是物件,任何都不例外,對所有值型別應用 Object.prototype.toString.call() 方法結果如下:
console.log(Object.prototype.toString.call(123)) //"[object Number]" console.log(Object.prototype.toString.call('123')) //"[object String]" console.log(Object.prototype.toString.call(undefined)) //"[object Undefined]" console.log(Object.prototype.toString.call(true)) //"[object Boolean]" 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(){})) //"[object Function]"
可以看出,Object.prototype.toString可以精確的判斷各種型別的資料。
判斷是否為函式
function isFunction(it) {
return Object.prototype.toString.call(it) === '[object Function]';
}
相容性寫法判斷是否為陣列
function isArray(arr){ //自己封裝的一個函式isArray(),用於判斷函式傳入的引數是否是陣列;
if(typeof Array.isArray === "undefined"){ //Array.isArray()是ES5中新增的方法,先判斷下其是否是undefined,如果是未定義的話執行該段函式,定義一個Array.isArray()方法;
Array.isArray = function(brr){ //如果未定義,則定義函式並傳入引數;
return Object.prototype.toString.call(brr)=="[object Array]" //通過js中的Object.prototype.toString方法,返回一個判斷,假設引數物件值屬於陣列內建型別,判斷時,如果返回true則是陣列,否則不是;
}
}
return Array.isArray(arr); //返回該方法,呼叫isArray()相當於呼叫Array.isArray();
}