EnumeratorおよびDictionaryの覚書
JScript(IEのJavaScript実装)なので、他のブラウザでは動かないし、普通のWebページでは使わないこと。
Enumeratorオブジェクト
メソッド4つのみのシンプルなオブジェクト。
var e = new Enumerator(collection);
メソッド | 説明 |
---|---|
e.moveFirst() | ポインタを最初の項目に設定する。 |
e.moveNext() | ポインタを次の項目に設定する。 |
e.item() | ポインタが指す項目を返す。 |
e.atEnd() | これ以上ポインタが指す項目がない場合trueを、そうでなければfalseを返す。 |
- 以下のようにして走査するのが基本のようだ(この例だとe.moveFirst()は必要ないように思える)。
var e = new Enumerator(collection); for (e.moveFirst(); !e.atEnd(); e.moveNext()) { // e.item() を使った処理 }
- FileSystemObjectのFilesコレクションなど、直接扱えないコレクションを走査するために使うもののようだけど、普通の配列やHTMLCollectionにも使えるので、Enumeratorを拡張すると便利かもしれない。
Enumerator.prototype.each = function (fn) { for (this.moveFirst(); !this.atEnd(); this.moveNext()) fn(this.item()); }; // ホスト名の異なるリンクにtarget="_blank"を設定 new Enumerator(document.all.tags('a')).each(function (a) { if (a.href && a.href.indexOf(location.hostname) === -1) a.target = '_blank'; });
ユーザー定義オブジェクトは、Enumeratorを通すとinstanceof演算子が機能しなくなる。
Dictionaryオブジェクト
JScriptではオブジェクトで代用できるので、オブジェクトでいいと思う。
var dic = new ActiveXObject('Scripting.Dictionary');
プロパティ・メソッド | 説明 |
---|---|
dic.Add(key, value) |
ペアを追加。既にkeyが存在していた場合、エラー。 |
dic.Key(key) = newkey |
キーの変更。 |
dic.Item(key) = newitem |
値の取得。あるいは値の変更。あるいはペアの追加。 |
dic.Remove(key) |
ペアの削除。 |
dic.RemoveAll() |
全てのペアを削除。 |
dic.Exists(key) |
キーが存在するか否か(true/false)。 |
dic.Count() |
ペアの数。 |
dic.Keys() |
全てのキーを格納したVBArrayを返す。 |
dic.Items() |
全ての値を格納したVBArrayを返す。 |
key
は文字列と数値を区別するので、dic(0)
とdic('0')
は別。Item
は省略できる。dic('j') = 'JScript'; // dic.Item('j') = 'JScript'; と同義 alert(dic('j')); // alert(dic.Item('j')); と同義
dic.Keys()
、dic.Items()
の戻り値のVBArrayは、そのままでは使えないので、以下のようにしてArrayに変換する。var keys = (new VBArray(dic.Keys())).toArray(); // new VBArray()を噛ませなくてもいい? var keys = dic.Keys().toArray();