使用indexOf检索数组值

时间:2013-06-11 20:33:30

标签: javascript arrays loops indexing

我创建了一个类似下面的数组,

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 个答案:

答案 0 :(得分:4)

不确定我是否已经得到它,但是要开始在good morning迭代并在hey!结束,只需使用字符串的索引作为循环中的开始和结束?

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

var start = arr.indexOf('good morning'),
    ends  = arr.indexOf('hey!');

for (var i=start; i<ends; i++) {
    console.log(arr[i]);
}

FIDDLE

您可以使用slice()做类似的事情吗?

arr.slice(arr.indexOf('good morning'), arr.indexOf('hey!')).forEach(function(s) {
    console.log(s)
});

FIDDLE

答案 1 :(得分:0)

for (var x = array.indexOf("good morning"); x < array.indexOf("hey!"); ++x)

但老实说,我没有看到它的使用......

答案 2 :(得分: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])
}

答案 3 :(得分:0)

根据您的具体问题,使用内置方法可能是更好的方法,但这里有一个如何扩展Array原型的示例,如果您真的想要一个更符合此需求的args处理器式迭代器。

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

引发错误:

-missing handler

第一个位置的

-no'dis'论点

- 'dis'之前的'dat'

相关问题