admin管理员组文章数量:1328571
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
2 Answers
Reset to default 6There'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.
本文标签: javascriptHow to get the position of the second occurrenceStack Overflow
版权声明:本文标题:javascript - How to get the position of the second occurrence? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742259529a2442252.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论