JavaScript indexOf()란?

김진원·2022년 11월 20일

JS

목록 보기
5/11
post-thumbnail

indexOf 정의

indexOf()메서드는 원하는 내용을 문자열에선 존재여부로 / 배열에선 해당 index로 반환 해주는 함수다.

indexOf 사용 예시

'Blue Whale'.indexOf('Blue');     // returns  0
'Blue Whale'.indexOf('Blute');    // returns -1
'Blue Whale'.indexOf('Whale', 0); // returns  5
'Blue Whale'.indexOf('Whale', 5); // returns  5
'Blue Whale'.indexOf('Whale', 7); // returns -1
'Blue Whale'.indexOf('');         // returns  0
'Blue Whale'.indexOf('', 9);      // returns  9
'Blue Whale'.indexOf('', 10);     // returns 10
'Blue Whale'.indexOf('', 11);     // returns 10

문자열에서 사용 시 존재하지 않을 때 -1을 반환한다.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

마찬가지로 배열에서도 존재하지 않을 때 -1을 반환합니다.

배열 내 해당 요소 모두 찾기

var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]
profile
사용자의 관점에 대해 욕심이 많은 개발자

0개의 댓글