JS基礎——數據類型判斷typeof、instanceof、Object.prototype.toString

  1. typeof用在基本數據類型和函數時,返回其對應類型的描述,對於引用類型都返回爲object.
  2. instanceof沒法判斷基本數據類型,對於引用類型數據,返回其其對應類型。
  3. Object.prototype.toString不管基本數據類型仍是引用類型返回其對應類型。

對應測試結果以下:函數

typeof test instanceof Object.prototype.toString.call(test)
var test = 'xuriliang'; string test instanceof String //false [object String]
var test = 27; number test instanceof Number //false [object Number]
var test = true; boolean test instanceof Boolean //false [object Boolean]
var test = [1,2,3]; object test instanceof Array //true [object Array]
test instanceof Object //true
var test = null; object test instanceof Object //false [object Null]
var test = undefined; undefined test instanceof Object //false [object Undefined]
var test = new String('xuriliang') object test instanceof String //true [object String]
test instanceof Object //true
var test = new Number(27) object test instanceof Number //true [object Number]
test instanceof Object //true
var test = new Boolean(true) object test instanceof Boolean //true [object Boolean]
test instanceof Object //true
var test = new Array(1,2,3) object test instanceof Array //true [object Array]
test instanceof Object //true
var test = function(){} function test instanceof Function //true [object Function]
test instanceof Object //true
var test = /d/ object test instanceof RegExp //true [object RegExp]
test instanceof Object //true
相關文章
相關標籤/搜索