首页 > 其他 > 详细

判断数据类型几种方法

时间:2018-10-17 12:58:30      阅读:110      评论:0      收藏:0      [点我收藏+]

常用的判断数据类型的方法主要有: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]

 

 

 

 

 

   

 

判断数据类型几种方法

原文:https://www.cnblogs.com/zpxm/p/9803101.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!