javascript數據類型檢測的幾種方式

類型檢測的方法

  1. typeof函數

  2. instanceofspa

  3. Object.protype.toStringprototype

  4. constructorcode

  5. duck type:鴨子類型對象

clipboard.png

typeof

返回一個字符串,適合函數對象和基本類型的判斷ip

var a = 123;
var b = '123';
var c = false;
var d = null;
var e = undefined;
var f = {};
var g = function(){};
var h = [];
var i = NaN;

console.log(typeof a);
console.log(typeof b);
console.log(typeof c);
console.log(typeof d);
console.log(typeof e);
console.log(typeof f);
console.log(typeof g);
console.log(typeof h);
console.log(typeof i);

clipboard.png

instanceof

返回一個布爾值,判斷對象類型(基於原型鏈的方式)原型鏈

原理:
左邊對象的原型鏈(_proto_原型)上是否有右邊構造函數的prototype對象屬性字符串

clipboard.png

var a = 123;
    var b = '123';
    var c = false;
    var d = null;
    var e = undefined;
    var f = {};
    var g = function(){};
    var h = [];
    var i = NaN;
    console.log(a instanceof Number);
    console.log(b instanceof String);
    console.log(c instanceof Boolean);
    console.log(d instanceof Object);
    console.log(e instanceof Object);
    console.log(f instanceof Object);
    console.log(g instanceof Function);
    console.log(h instanceof Array);
    console.log(i instanceof Number);//NaN是基本類型

這麼多false就說明instanceof不適合用於基本數據類型!!
clipboard.png原型

Object.prototype.toString

var oP = Object.prototype,
toString = oP.toString;
console.log(toString.call(123));//[object Number]
console.log(toString.call('123'));//[object String]
console.log(toString.call(false));//[object Boolean]
console.log(toString.call(undefined));//[object Undefined]
console.log(toString.call(null));//[object Null]
console.log(toString.call({a: '123'}));//[object Object]
console.log(toString.call(/123/));//[object RegExp]
console.log(toString.call([123]));//[object Array]
console.log(toString,call(Date));//[object Function]

注意:IE6/7/8 Object.prototype.toString.call(null/undefined)返回的是[object Object]it

constructor

var a = 123;
var b = '123';
var c = false;
var d = null;
var e = undefined;
var f = {};
var g = function(){};
var h = [];
var i = NaN;
console.log(a.constructor == Number);
console.log(b.constructor == String);
console.log(c.constructor == Boolean);
// console.log(d.constructor == Object);
// console.log(e.constructor == Object);
console.log(f.constructor == Object);
console.log(g.constructor == Function);
console.log(h.constructor == Array);
console.log(i.constructor == Number);

clipboard.png

相關文章
相關標籤/搜索