2014-10-02 2 views
1

말 단지 첫번째하지를 받고 :, 배열에 같이 IndexOf 방법을 사용하여 내가 배열을 포함하는 문자열이있는 모든 인덱스와

var array = ["test","apple","orange","test","banana"]; 

일부 문자열은 정확히 같은 (테스트) 있습니다. 문자열 테스트이 첫 번째 indexOf가 아니라 배열에있는 배열의 모든 인덱스를 가져 오려고한다고 가정 해보십시오. jQuery를 사용하지 않고 가능한 한 빨리이 문제에 대한 좋은 해결책이 있습니까, 결과적으로 0,2를 얻는가?

감사

더 나은이

var indices = []; 

array.forEach(function(currentItem, index) { 
    if (currentItem === "test") { 
     indices.push(index); 
    } 
}); 

console.log(indices); 

같은

+1

이것은 정확히 내 문제와 비슷합니다. http://stackoverflow.com/questions/20798477/how-to-find-index-of-all-occurrences-of-an-element-in-array – leopik

답변

0

당신이 사용할 수있는 내장 Array.prototype.forEach 당신이 솔루션을 원하기 때문에이

var indices = array.reduce(function(result, currentItem, index) { 
    if (currentItem === "test") { 
     result.push(index); 
    } 
    return result; 
}, []); 

console.log(indices); 

같은 Array.prototype.reduce를 사용할 수도 IE에서 작동하는 , 당신은 평범한 구식 루프를 가지고 싶을 것입니다.

var indices = [], i; 

for (i = 0; i < array.length; i += 1) { 
    if (array[i] === "test") { 
     indices.push(i); 
    } 
} 

console.log(indices);