码迷,mamicode.com
首页 > 编程语言 > 详细

在javaScript中检测数据类型的几种方式

时间:2019-04-21 19:59:53      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:esc   cto   tostring   script   类型   基本类型   pre   keyword   原型链   

类型检测的方法

  1. typeof

  2. instanceof

  3. Object.protype.toString

  4. constructor

  5. duck type:鸭子类型

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);

instanceof

返回一个布尔值,判断对象类型(基于原型链的方式)

原理:
左边对象的原型链(_proto_原型)上是否有右边构造函数的prototype对象属性

    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不适合用于基本数据类型!!

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);

在javaScript中检测数据类型的几种方式

标签:esc   cto   tostring   script   类型   基本类型   pre   keyword   原型链   

原文地址:https://www.cnblogs.com/lguow/p/10746341.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!