JavaScript判斷變數是對象還是數組的方法,javascript數組
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。
Javascript怎判斷一個變數是普通變數還是數組還是對象?
1、使用typeof操作符檢測變數類型
數組、Null、Object 為 object 類型
字串 為 string 類型
true和false 為 boolean 類型
整型、浮點型為 number 類型
2、如果要區分數組和非數組對象,需要使用建構函式來判斷
if(arr.constructor==Array)
// arr 是數組
else
// arr 不是數組
怎判斷javascript中的變數是否為數組?
var array = [];
alert(Object.prototype.toString.call(array) == '[object Array]')