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

從上例咱們能夠看出, typeof  判斷對象和數組都返回object,所以它沒法區分對象和數組。spa

2.instanceof

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

由於數組屬於object中的一種,因此數組instanceof object,也是true.prototype

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

instanceof不能區分基本類型string和boolean,除非是字符串對象和布爾對象。如上例所示。code

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();blog

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]"

封裝一個判斷數組和對象的方法string

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方法的在被調用的時候,會執行以下的操做步驟: io

1. 獲取對象的類名(對象類型)。  

[[Class]]是一個內部屬性,全部的對象(原生對象和宿主對象)都擁有該屬性.在規範中,[[Class]]是這麼定義的: 
內部屬性,[[Class]] 一個字符串值,代表了該對象的類型。
2. 而後將[object  獲取的對象類型的名]組合爲字符串 
3. 返回字符串 「[object Array]」 。

5.jQuery中的  $.type接口

$.type(obj) ;

$.isArray(obj);

$.isFunction(obj);

$.isPlainObject(obj);

$.type([])    //array
$.isArray([]); //true
$.isFunction(function(){}); //true
$.isPlainObject({}); //true
$.isPlainObject([]); //false
相關文章
相關標籤/搜索