0

以下のような配列を作成しました。

var array = ['hello', 'hi', 'good morning', 'sweet', 'cool', 'nice', 'hey!', 'how you doin?', 'Thanks!'];

var index = array.indexOf('good morning')//This will return 2 since 'good morning' is located in 2 in index.

私の質問は、「おはよう」から始まり「ねえ!」で終わる配列内の 5 つの値すべてをループするにはどうすればよいですか?

これは、次のように for ループ ステートメントを使用することで簡単に実行できることがわかっています。

for (x = 2; x<= 6; x++){
} 

しかし、インデックス値 2 を指定するだけでこれを達成する別の方法を探しています。

4

4 に答える 4

0

特定の問題によっては、おそらく組み込みメソッドを使用してそれを行うより良い方法ですが、この正確なニーズに合わせて調整された引数を使用して、よりハンドラースタイルのイテレーターが本当に必要な場合は、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」

于 2013-06-11T21:35:46.910 に答える
0
var array = ['hello', 'hi', 'good morning', 'sweet', 'cool', 'nice', 'hey!', 'how you doin?', 'Thanks!'];

startIndex = array.indexOf('good morning');
endIndex = array.indexOf('hey!');

for (x = startIndex; x < endIndex; x++){
    console.log(array[x])
}
于 2013-06-11T20:42:47.283 に答える