JavaScript判斷變量是對象還是數組的方法,要怎么判斷呢?其實在使用typeof進行判斷的時候一般顯示的返回值為“object”,今天是錯新技術頻道小編分享的方法,希望能幫到您。
typeof都返回object
在JavaScript中所有數據類型嚴格意義上都是對象,但實際使用中我們還是有類型之分,如果要判斷一個變量是數組還是對象使用typeof搞不定,因為它全都返回object
復制代碼 代碼如下:
var o = { 'name':'lee' };
var a = ['reg','blue'];
?
document.write( ' o typeof is ' + typeof o);
document.write( ' <br />');
document.write( ' a typeof is ' + typeof a);
執行:
?
復制代碼 代碼如下:
?
o typeof is object
a typeof is object
因此,我們只能放棄這種方法,要判斷是數組or對象有兩種方法
?
第一,使用typeof加length屬性
數組有length屬性,object沒有,而typeof數組與對象都返回object,所以我們可以這么判斷
復制代碼 代碼如下:
var o = { 'name':'lee' };
var a = ['reg','blue'];
?
var getDataType = function(o){
??? if(typeof o == 'object'){
??????? if( typeof o.length == 'number' ){
??????????? return 'Array';
??????? }else{
??????????? return 'Object';???
??????? }
??? }else{
??????? return 'param is no object type';
??? }
};
?
alert( getDataType(o) );??? // Object
alert( getDataType(a) );??? // Array
alert( getDataType(1) );??? // param is no object type
alert( getDataType(true) ); // param is no object type
alert( getDataType('a') );? // param is no object type
?
第二,使用instanceof
使用instanceof可以判斷一個變量是不是數組,如:
復制代碼 代碼如下:
var o = { 'name':'lee' };
var a = ['reg','blue'];
?
alert( a instanceof Array );? // true
alert( o instanceof Array );? // false
也可以判斷是不是屬于object
?
復制代碼 代碼如下:
?
var o = { 'name':'lee' };
var a = ['reg','blue'];
?
alert( a instanceof Object );? // true
alert( o instanceof Object );? // true
但數組也是屬于object,所以以上兩個都是true,因此我們要利用instanceof判斷數據類型是對象還是數組時應該優先判斷array,最后判斷object
?
復制代碼 代碼如下:
?
var o = { 'name':'lee' };
var a = ['reg','blue'];
?
var getDataType = function(o){
??? if(o instanceof Array){
??????? return 'Array'
??? }else if( o instanceof Object ){
??????? return 'Object';
??? }else{
??????? return 'param is no object type';
??? }
};
?
alert( getDataType(o) );??? // Object
alert( getDataType(a) );??? // Array
alert( getDataType(1) );??? // param is no object type
alert( getDataType(true) ); // param is no object type
alert( getDataType('a') );? // param is no object type
如果你不優先判斷Array,比如:
?
復制代碼 代碼如下:
?
var o = { 'name':'lee' };
var a = ['reg','blue'];
?
var getDataType = function(o){
??? if(o instanceof Object){
??????? return 'Object'
??? }else if( o instanceof Array ){
??????? return 'Array';
??? }else{
??????? return 'param is no object type';
??? }
};
?
alert( getDataType(o) );??? // Object
alert( getDataType(a) );??? // Object
alert( getDataType(1) );??? // param is no object type
alert( getDataType(true) ); // param is no object type
alert( getDataType('a') );? // param is no object type
那么數組也會被判斷為object。
錯新技術頻道有大家想要學習的知識,希望閱讀完本文的朋友,在學習這方面知識上,能更進一步。