日々プログラミング言語の勉強をしている京四郎のブログ -14ページ目

日々プログラミング言語の勉強をしている京四郎のブログ

日々プログラムの勉強をしている人がプログラム関係の記事を書くブログ

けん配列か判定する関数

var is_array = function (value) {
 return value && typeof value === 'object' && value.constructor === Array;
};

var is_array2 = function (value) {
    return value && 
    typeof value === 'object' && 
    typeof value.length === 'number' && 
    typeof value.splice === 'function' && !(value.propertyIsEnumerable('length'));
};


メラメラフレームで生成された配列がis_array関数でtrue、is_array2関数でfalseになるサンプル

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title></title>
</head>
<body>
<h2>Javascript The Good Parts</h2>

6章 配列<br/>
配列かどうか判定 P70<br/>

<br/>
<iframe name="hoge" src=""></iframe>
<br/>
 <iframe name="hoge2" src=""></iframe> 
<br/>

<script type="text/javascript">

var is_array = function (value) {
 return value && typeof value === 'object' && value.constructor === Array;
};


var is_array2 = function (value) {
return value && 
typeof value === 'object' && 
typeof value.length === 'number' && 
typeof value.splice === 'function' && !(value.propertyIsEnumerable('length'));
};

var frm_doc=parent.frames[0].Array(1,2,"demon-uploader",2014,true);

document.writeln("\n<br/>");
document.writeln("frm_doc[0]="+frm_doc[0]+"\n<br/>");
document.writeln("frm_doc[1]="+frm_doc[1]+"\n<br/>");
document.writeln("frm_doc[2]="+frm_doc[2]+"\n<br/>");
document.writeln("frm_doc[3]="+frm_doc[3]+"\n<br/>");
document.writeln("frm_doc[4]="+frm_doc[4]+"\n<br/>");
document.writeln("\n<br/>");
document.writeln("is_array(frm_doc)="+is_array(frm_doc)+"\n<br/>");
document.writeln("is_array2(frm_doc)="+is_array2(frm_doc)+"\n<br/>");

var frm_doc2 = new hoge2.Array(1,2,3); 
document.writeln("\n<br/>");
document.writeln("is_array(frm_doc)="+is_array(frm_doc2)+"\n<br/>");
document.writeln("is_array2(frm_doc)="+is_array2(frm_doc2)+"\n<br/>");

/*
実行結果

frm_doc[0]=1 
frm_doc[1]=2 
frm_doc[2]=demon-uploader 
frm_doc[3]=2014 
frm_doc[4]=true 

is_array(frm_doc)=false 
is_array2(frm_doc)=true 

is_array(frm_doc)=false 
is_array2(frm_doc)=true 

*/
</script>
</body>
</html>


へび解説

Javascript Good Partsには、オブジェクトと配列を見分ける関数としてis_array関数が載っている。 is_arrayは、異なるグローバルオブジェクト(ウインドウやフレームなど)で作成された配列を見分けることができない。
外部からもたらされた配列を判別したい場合is_array2を使うとある。
※便宜的にis_array2とここでは書いているが、Good Partsではis_arrayと書いてある。

「異なるグローバルオブジェクト(ウインドウやフレームなど)で生成された配列」 とはどんなものなのか?
この記事では、フレームで生成された配列がis_array関数でtrue、is_array2関数でfalseになるサンプルを書いておきます。
ウインドウで生成された配列ってのは何か分かりません。誰か教えてください。


itigoQiitaに投稿した

【Javascript】配列とオブジェクトを見分ける

http://qiita.com/kyoshiro-obj/items/551240c68185fd47e2fe



おんぷ参考文献

Douglas Crockford 著 水野貴明 訳『JavaScript:The Good Parts』(オライリー・ジャパン発行、2008) p70-71

JavaScript:the good parts [ ダグラス・クロフォード ]
¥1,944
楽天