javascript数据类型检测的几种方式

类型检测的方法

  1. typeof

  2. instanceof

  3. Object.protype.toString

  4. constructor

  5. duck type:鸭子类型

clipboard.png

typeof

返回一个字符串,适合函数对象和基本类型的判断

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]

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

阅读 1.6k

推荐阅读