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

Posted 奔跑的太阳花

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在javaScript中检测数据类型的几种方式相关的知识,希望对你有一定的参考价值。

类型检测的方法

  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中检测数据类型的几种方式的主要内容,如果未能解决你的问题,请参考以下文章

数据类型检测的几种方式

检测数据类型的几种方式

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

JS中检测数据类型的几种方式及优缺点

JS中检测数据类型的几种方式及优缺点

js中检测数据类型的几种方法