判断数据类型几种方法

常用的判断数据类型的方法主要有:typeof,instanceof,constructor,Object.prototype.toString

下面来分别介绍

1、typeof:返回一个字符串,表示未经计算的操作数的类型。

     console.log(typeof 42);   // number   

     缺点:对于数组和对象或null 都会返回object

2、instanceof:用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
var auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car);       // true

// 因为Object是原型链的最顶端,所以在其原型链上的都会为true
console.log(auto instanceof Object);   // true  

        缺点:instanceof不能判断null和undefined

3、constructor:返回创建实例对象的 Object 构造函数的引用

var o = {};
o.constructor === Object; // true

var o = new Object;
o.constructor === Object; // true

var a = [];
a.constructor === Array; // true

var a = new Array;
a.constructor === Array // true

var n = new Number(3);
n.constructor === Number; // true

function Tree(name) {
   this.name = name;
}

var theTree = new Tree("Redwood");
console.log( theTree.constructor );   //function Tree(name){this.name=name}

     缺点:无法检测null,undefined

4、Object.prototype.toString

Object.prototype.toString.call(new Date)  // [object Date]

 

 

 

 

 

   

 

posted @ 2018-10-17 11:34  小小的忧愁  阅读(1523)  评论(0编辑  收藏  举报