在JavaScript中所有數據類型嚴格意義上都是對象,但實際使用中我們還是有類型之分,如果要判斷一個變量是數組還是對象使用typeof搞不定,因為它全都返回object。
使用typeof加length屬性
數組有length屬性,object沒有,而typeof數組與對象都返回object,所以我們可以這么判斷。
- var shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
shopping;
-
typeof shopping;
"object" -
var getDataType = function(shopping){
if(typeof shopping == 'object'){
if( typeof shopping.length == 'number' ){
return 'Array';
}else{
return 'Object';
}
}else{
return 'param is no object type';
}
};
alert( getDataType(shopping) );
原文鏈接:http://www.qttc.net/201306338.html