JavaScriptには、変数の方を取得するための手段として、typeofが準備されていますが、
こいつが不便で配列も連想配列(hash)もどちらも"object"と判定します。
配列か連想配列かの判定はできないのです。
ということで、配列ならarray,連想配列ならhash,その他ならそのままtypeofの値を戻す関数を作りました。
classOf:
function classOf(obj){
if((typeof obj)=="object"){
if(obj.length!=undefined)return "array";
else{for(t in obj){
if(obj[t]!=undefined)return "hash";
else return "object";
}}
}else return (typeof obj);
}
a = [0,1,2,3,4,5];
document.write(typeof a);// object
document.write(classOf(a));// array
b = {"a":"A", "b":"B"};
document.write(typeof b);// object
document.write(classOf(b));// hash
この記事にトラックバックする