數據類型的判斷 --Object.prototype.toString.call(obj)精準檢測對象類型

數據類型的判斷 typeof

typeof返回一個表示數據類型的字符串,返回結果包括:number、boolean、string、symbol、object、undefined、function等7種數據類型,但不能判斷null、array等函數

typeof Symbol();  // symbol 有效
typeof '';  // string 有效
typeof 1;  // number 有效
typeof true;  //boolean 有效
typeof undefined;  //undefined 有效
typeof new Function();  // function 有效
typeof null;  //object 無效
typeof [] ;  //object 無效
typeof new Date();  //object 無效
typeof new RegExp();  //object 無效

數據類型的判斷 instanceof

instanceof 是用來判斷A是否爲B的實例,表達式爲:A instanceof B,若是A是B的實例,則返回true,不然返回false。instanceof 運算符用來測試一個對象在其原型鏈中是否存在一個構造函數的 prototype 屬性,但它不能檢測null 和 undefined測試

[] instanceof Array; //true
{} instanceof Object;//true
new Date() instanceof Date;//true
new RegExp() instanceof RegExp//true
null instanceof Null//報錯
undefined instanceof undefined//報錯

嚴格運算符===

只能用於判斷null和undefined,由於這兩種類型的值都是惟一的。prototype

constructor

constructor做用和instanceof很是類似。但constructor檢測 Object與instanceof不同,還能夠處理基本數據類型的檢測。
細節問題code

  1. null 和 undefined 是無效的對象,所以是不會有 constructor 存在的,這兩種類型的數據須要經過其餘方式來判斷。
  2. 函數的 constructor 是不穩定的,這個主要體如今自定義對象上,當開發者重寫 prototype 後,原有的constructor 引用會丟失,constructor 會默認爲 Object

Object.prototype.toString.call()

Object.prototype.toString.call('') ;   // [object String]
Object.prototype.toString.call(1) ;    // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
相關文章
相關標籤/搜索