js判断对象类型

1.typeof

typeof只能判断区分基本类型,number、string、boolean、undefined和object,function;

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

typeof null; //object
typeof {};  //object;
typeof []; //object
let s = Symbol();
typeof s    //"symbol"
s instanceof Symbol  //false

 

从上例我们可以看出, typeof  判断对象和数组都返回object,因此它无法区分对象和数组。

2.instanceof

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

因为数组属于object中的一种,所以数组instanceof object,也是true.

var c='abc';
c instanceof String; //false
var d=new String();
d instanceof String  //true

instanceof不能区分基本类型string和boolean,除非是字符串对象和布尔对象。如上例所示。

3.constructor  

var o={};
o.constructor==Object  //true
var arr=[];
arr.constructor==Array  //true
arr.constructor==Object //false

可以看出constructor可以区分Array和Object。

var n=true;
n.constructor==Boolean  //true
var num=1;
num.constructor==Number  //true
var str='hello world';
str.constructor==String     //true

var num=new Number();

num.constructor==Number   //true

 

不过要注意,constructor属性是可以被修改的,会导致检测出的结果不正确

function Person(){
  
}
function Student(){
  
}
Student.prototype = new Person();
var John = new Student();
console.log(John.constructor==Student); // false
console.log(John.constructor==Person); // true
除了undefined和null,其他类型的变量均能使用constructor判断出类型.

4.Object.prototype.toString.call()   ---------最好用

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]"
Object.prototype.toString.call(null)
//"[object Null]"

 

封装一个判断数组和对象的方法

function typeObj(obj){
      var type=Object.prototype.toString.call(obj);
      if(type=='[object Array]'){
        return 'Array';
      }elseif(type=='[object  Object]'){
        return 'Object';
      }else{
        return "obj is not object or array"
      }

}

Object.prototype.toString方法的在被调用的时候,会执行如下的操作步骤: 

1. 获取对象的类名(对象类型)。  

[[Class]]是一个内部属性,所有的对象(原生对象和宿主对象)都拥有该属性.在规范中,[[Class]]是这么定义的: 
内部属性,[[Class]] 一个字符串值,表明了该对象的类型。
2. 然后将[object  获取的对象类型的名]组合为字符串 
3. 返回字符串 “[object Array]” 。

5.jQuery中的  $.type接口

$.type(obj) ;

$.isArray(obj);

$.isFunction(obj);

$.isPlainObject(obj);

$.type(null) //null
$.type([])    //array
$.isArray([]); //true
$.isFunction(function(){}); //true
$.isPlainObject({}); //true
$.isPlainObject([]); //false
$.isPlainObject(null); //false

 

posted @ 2018-07-29 17:42  sunmarvell  阅读(32285)  评论(2编辑  收藏  举报