最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the position of the second occurrence? - Stack Overflow

programmeradmin6浏览0评论

Let's say I have this array:

var a = [1,2,99,3,4,99,5];

I would like to get the position of the second 99, something like:

a.indexOf(99, 2) // --> 5

However the second argument in indexOf just tells where to start the search. Is there any built in functions to make this? If not how would you do it?

Thanks!

Let's say I have this array:

var a = [1,2,99,3,4,99,5];

I would like to get the position of the second 99, something like:

a.indexOf(99, 2) // --> 5

However the second argument in indexOf just tells where to start the search. Is there any built in functions to make this? If not how would you do it?

Thanks!

Share Improve this question edited Jan 23, 2013 at 12:28 Adam Halasz asked Jan 23, 2013 at 12:21 Adam HalaszAdam Halasz 58.3k67 gold badges153 silver badges216 bronze badges 1
  • a.indexOf(99, a.indexOf(99)+1) – John Dvorak Commented Jan 23, 2013 at 12:26
Add a ment  | 

2 Answers 2

Reset to default 6

There's only indexOf and lastIndexOf. You could loop over it:

var a = [1,2,99,3,4,99,5];
var matches = []
for (var i=0; i<a.length; i++){
    if (a[i] == 99) {
        matches.push(i)
    }
}
console.log(matches); // [2, 5]

If you always want the second occurrence Jan's method is also good:

a.indexOf(99, a.indexOf(99) + 1)

The indexOf call on the right finds the first occurrence, +1 then limits the search to the elements that follow it.

There is no built in function, but you can easily create your own, by iteratively applying indexOf:

function indexOfOccurrence(haystack, needle, occurrence) {
    var counter = 0;
    var index = -1;
    do {
        index = haystack.indexOf(needle, index + 1);
    }
    while (index !== -1 && (++counter < occurrence));
    return index;
}

// Usage
var index = indexOfOccurrence(a, 99, 2);

But Matt's solution might be more useful.

发布评论

评论列表(0)

  1. 暂无评论