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,因此它無法區分對象和數組。
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.
var c='abc'; c instanceof String; //false var d=new String(); d instanceof String //trueinstanceof不能區分基本類型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 //truevar 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]"封裝一個判斷數組和對象的方法
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([]) //array $.isArray([]); //true $.isFunction(function(){}); //true $.isPlainObject({}); //true $.isPlainObject([]); //false?
更多專業前端知識,請上 【猿2048】www.mk2048.com
總結
- 上一篇: 为自己写程序之JavsScript代码段
- 下一篇: CSS中可继承的属性