检测对象类型

现在掌握的检测对象类型有几种:

  1. typeof
  2. instanceof
  3. Object.prototype.toString.call()
  4. 严格比较运算符

根据不同的情况做不同的选择吧。

  1. typeof

typeof 返回的结果是字符串,返回如下几个结果:“number”、“string”、“boolean”、“object”、“function” 和 “undefined”,即它只可以判断这几种基本类型

console.log(typeof(2));   //number
console.log(typeof('name'));    //string
console.log(typeof(true));    //boolean
console.log(typeof({name:'1'}));    ///object
console.log(typeof(function(){}));    //function
console.log(typeof(null));    //object
console.log(typeof(undefined));   //undefined

typeof 的局限性就是无法判断对象的具体类型,object、array、null 这些数据类型都是 object

  1. instance of

instanceof运算符用来判断一个构造函数的prototype属性所指向的对象是否存在另外一个要检测对象的原型链上

function Person(){};
var p =new Person();
console.log(p instanceof Person);  // true
var str = new String('name');
console.log(str instanceof String); // true
var str = new Number('10');

str instanceof String // true

另一个用途是判断实例是否属于它的父类

function Person(){};
function Student(){};
var p =new Person();
Student.prototype=p;//继承原型
var s=new Student();
console.log(s instanceof Student);//true
console.log(s instanceof Person);//true
  1. Object.prototype.toString.call()

应用的场景最广,对于每种数据类型,它都可以作出判断

console.log(Object.prototype.toString.call("name"));//[object String]
console.log(Object.prototype.toString.call(1));//[object Number]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call({name: "name"}));//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(new Date));//[object Date]
console.log(Object.prototype.toString.call(/\d/));//[object RegExp]
function Person(){};
console.log(Object.prototype.toString.call(new Person));//[object Object]
  1. 严格比较运算符
    严格比较运算符(===)用在判断 undefined 和 null 上还是挺好用的。
var a;
var b = null
console.log(a === undefined);  //true
console.log(b === null);  // true

注意在实际的应用中,用判断的时候,最好不要直接用 if(a) {} 这样的判断形式,还是进行类型判断比较好。

猜你喜欢

转载自blog.csdn.net/kelly0721/article/details/86243092
今日推荐