特定の問題によっては、おそらく組み込みメソッドを使用してそれを行うより良い方法ですが、この正確なニーズに合わせて調整された引数を使用して、よりハンドラースタイルのイテレーターが本当に必要な場合は、Array プロトタイプを拡張する方法の例を次に示します。
Array.prototype.disToDat = function(dis){
if(dis===undefined || typeof dis === 'function'){
throw new Error('No dis. You need dat and deserve to be dissed');
}
dis = this.indexOf(dis);
if(typeof arguments[1] === 'function'){
var dat = this.length - 1; //optional dat - runs to the end without
var handler = arguments[1];
}
else if(typeof arguments[2] === 'function'){
var dat = this.indexOf(arguments[1]);
if(dis > dat){ throw new Error('Dat is before dis? What is dis!?'); }
var handler = arguments[2];
}
else{
throw new Error(
"You can't handle dis or dis and dat without a handler."
);
}
if(dis === -1 || dat === -1){ return null; }
for(var i=dis; i<=dat; i++){
handler(this[i]);
}
}
使用法:
['a','b','c','d','e'].disToDat('b', 'd', function(disOne){ console.log(disOne); });
//dis and dat
['a','b','c','d','e'].disToDat('b', function(disOne){ console.log(disOne); });
//without optional dat, it just goes to the end
次のエラーをスローします。
-行方不明のハンドラー
-最初の位置に「dis」引数はありません
-「dis」の前に「dat」