indexOf 메서드는 배열과 문자열에서 특정 요소의 인덱스를 검색하는 데 사용됩니다. 이 메서드는 배열의 시작부터 끝까지 요소를 찾아 지정한 요소를 처음 발견한 인덱스를 반환합니다. 만약 배열에 해당 요소가 없다면 -1을 반환합니다.
사용법
array.indexOf(searchElement[, fromIndex])
-array: 검색을 수행할 배열, 문자열.
-searchElement: 찾고자 하는 요소.
-fromIndex (선택 사항): 검색을 시작할 인덱스. 이 매개변수를 지정하면 해당 인덱스부터 검색을 시작합니다. 생략하면 검색은 배열의 처음부터 시작됩니다.
활용 예제
<script>
//기본 사용법
var fruits = ['apple', 'banana', 'cherry', 'date'];
var index = fruits.indexOf('cherry');
console.log(index); // 2 (인덱스는 0부터 시작하므로 'cherry'는 배열에서 2번째 요소에 있음)
var notFoundIndex = fruits.indexOf('grape');
console.log(notFoundIndex); // -1 (배열에 'grape' 요소가 없으므로 -1을 반환)
//1.배열에서 특정 요소의 모든 인덱스를 찾기
var fruits = ['apple', 'banana', 'cherry', 'apple', 'date', 'apple'];
var searchElement = 'apple';
var indexes = [];
var currentIndex = fruits.indexOf(searchElement);
while (currentIndex !== -1) {
indexes.push(currentIndex);
currentIndex = fruits.indexOf(searchElement, currentIndex + 1);
}
console.log(indexes); // [0, 3, 5]
//2.fromIndex 매개변수 활용
var fruits = ['apple', 'banana', 'cherry', 'apple', 'date', 'apple'];
var searchElement = 'apple';
var fromIndex = 2;
var index = fruits.indexOf(searchElement, fromIndex);
console.log(index); // 3 (2 이후부터 검색하여 첫 번째 'apple'을 찾음)
//3.배열 내에서 요소의 존재 확인
var fruits = ['apple', 'banana', 'cherry', 'date'];
var searchElement = 'grape';
if (fruits.indexOf(searchElement) !== -1) {
console.log(searchElement + ' exists in the array.');
} else {
console.log(searchElement + ' does not exist in the array.');
}
//4.문자열에서 사용하기
var text = "This is a sample text, and we'll search for a substring in it.";
var substring = "sample";
var index = text.indexOf(substring);
if (index !== -1) {
console.log("Substring found at index " + index);
} else {
console.log("Substring not found in the text.");
}
</script>
1. 기본 사용법: indexOf 메서드를 배열에서 사용하는 기본 사용법을 보여줍니다. fruits 배열에서 'cherry'와 'grape'를 검색하여 해당 요소의 인덱스를 반환합니다.
2. 배열에서 특정 요소의 모든 인덱스 찾기: 배열에서 특정 요소 apple의 모든 인덱스를 찾는 방법을 보여줍니다. indexOf 메서드를 활용하여 해당 요소의 모든 인덱스를 찾아 배열에 저장하고 출력합니다.
3. fromIndex 매개변수 활용: fromIndex 매개변수를 사용하여 배열에서 특정 요소 apple를 검색하는 방법을 설명합니다. 검색을 시작하는 인덱스를 지정해서 검색하고 있습니다.
4. 배열 내에서 요소의 존재 확인: 배열에서 요소 grape의 존재를 확인하는 방법을 보여줍니다. indexOf를 사용하여 요소를 찾고, 반환된 값이 -1인지 여부를 통해 요소의 존재 여부를 판단합니다.
5. 문자열에서 사용하기: indexOf 메서드를 문자열에서 사용하는 예제입니다. 주어진 문자열에서 sample 부분 문자열을 검색하고 해당 위치를 출력합니다.
'개발이야기 > 자바스크립트' 카테고리의 다른 글
[자바스크립트] Google Charts(구글 차트) 사용법, 예제, 차트 그리기 (0) | 2023.10.31 |
---|---|
[자바스크립트] C3.js chart 사용법, 예제, 차트 그리기 (막대, 선, 원, 도넛, 파이 그래프) (0) | 2023.10.27 |
[자바스크립트] typeof 연산자 사용해서 변수와 값의 데이터 타입 확인하기 (0) | 2023.10.12 |
[자바스크립트] DOMContentLoaded와 load 이벤트 차이점 (순서, 사용법, 예제) (0) | 2023.10.06 |
[자바스크립트] e.preventDefault(), e.stopPropagation() 이벤트 제어하기 (사용법, 예제, 차이점) (0) | 2023.10.05 |
댓글