javaScript判断对象类型

javaScript判断对象类型

目前js自带的有很多方法可以判断对象的类型,比如typeof,instanceof,constructor,Object.prototype.toString.call。最好的最准确的是第四种:Object.prototype.toString.call。我们先来说说前三种的弊端:

1.typeof

typeof只能区分js的基本类型和对象类型以及function。但对于数组和object并不能有效区分。

typeof 0;  //number;
typeof true;  //boolean;
typeof undefined;  //undefined;
typeof "hello world"   //string;
typeof function(){};   //function;

typeof null; //object
typeof {};  //object;
typeof []; //object

2.instanceof

instanceof也同样无法区别对象和数组。因为数组也是object的一种,所以在判断的时候也会返回true;

var a={};
a instanceof Object  //true
a intanceof Array     //false
var b=[];
b instanceof Array  //true
b instanceof  Object //true

3.constructor 

constructor是可以判断数组和object类型的,但是遇到undefined和null时,会报错。

var o={};
o.constructor==Object  //true
var arr=[];
arr.constructor==Array  //true
arr.constructor==Object //false
        
var undefin,
    nl=null;
console.log(o.constructor==Object)//true
console.log(undefin.constructor);//Cannot read property 'constructor' of undefined
console.log(nl.constructor);//Cannot read property 'constructor' of null

4.Object.prototype.toString.call()

可以判断所有类型,返回string字符串;

var undefin;
Object.prototype.toString.call(undefin);//[object Undefined]
Object.prototype.toString.call(null);//[object Null]
Object.prototype.toString.call(123)//[object Number]
Object.prototype.toString.call('str')//[object String]
Object.prototype.toString.call(true)//[object Boolean]
Object.prototype.toString.call({})//[object Object]
Object.prototype.toString.call([])//[object Array]

参考博客:https://www.cnblogs.com/sunmarvell/p/9386075.html

 

你可能感兴趣的:(javaScript)