라이브러리
[JAVASCRIPT] arr.findIndex(callback) - 조건을 만족하는 첫 번째 요소의 인덱스 반환
arr.findIndex(callback)
`arr.findIndex(callback)`는 배열 `arr` 내에서 첫 번째 요소의 인덱스를 찾는 메서드입니다. 이 메서드는 제공된 콜백 함수 `callback`를 사용하여 요소를 검색합니다. 콜백 함수는 `element`와 `index`를 인자로 받으며, `element`는 배열의 현재 요소이며, `index`는 요소의 인덱스입니다.
콜백 함수는 `true`를 반환하는 경우, 해당 요소를 찾았을 때 `findIndex` 메서드는 그 요소의 인덱스를 반환합니다. 콜백 함수는 `false`를 반환하는 경우, 해당 요소를 찾지 못했을 때 `findIndex` 메서드는 `-1`을 반환합니다.
예제
#hostingforum.kr
javascript
// 예제 1: 배열 내에서 특정 요소 찾기
const arr = [1, 2, 3, 4, 5];
const index = arr.findIndex((element) => element === 3);
console.log(index); // 2
// 예제 2: 배열 내에서 특정 요소 찾기 (없는 경우)
const arr2 = [1, 2, 4, 5];
const index2 = arr2.findIndex((element) => element === 3);
console.log(index2); // -1
콜백 함수
콜백 함수는 `findIndex` 메서드의 인자로 전달됩니다. 콜백 함수는 두 개의 인자를 받습니다.
* `element`: 현재 요소
* `index`: 요소의 인덱스
콜백 함수는 `true`를 반환하는 경우, 해당 요소를 찾았을 때 `findIndex` 메서드는 그 요소의 인덱스를 반환합니다. 콜백 함수는 `false`를 반환하는 경우, 해당 요소를 찾지 못했을 때 `findIndex` 메서드는 `-1`을 반환합니다.
예제
#hostingforum.kr
javascript
// 예제 3: 콜백 함수 사용하기
const arr3 = [1, 2, 3, 4, 5];
const index3 = arr3.findIndex((element, index) => {
console.log(`현재 요소: ${element}, 인덱스: ${index}`);
return element === 3;
});
console.log(index3); // 2
배열의 요소가 여러 개일 때
`findIndex` 메서드는 배열의 첫 번째 요소를 찾을 때까지 검색을 계속합니다. 만약 배열의 요소가 여러 개일 때, `findIndex` 메서드는 첫 번째 요소의 인덱스를 반환합니다.
예제
#hostingforum.kr
javascript
// 예제 4: 배열의 요소가 여러 개일 때
const arr4 = [1, 2, 3, 3, 5];
const index4 = arr4.findIndex((element) => element === 3);
console.log(index4); // 2
배열이 비어 있을 때
`findIndex` 메서드는 빈 배열의 경우 `-1`을 반환합니다.
예제
#hostingforum.kr
javascript
// 예제 5: 배열이 비어 있을 때
const arr5 = [];
const index5 = arr5.findIndex((element) => element === 3);
console.log(index5); // -1
배열의 요소가 null 또는 undefined일 때
`findIndex` 메서드는 배열의 요소가 `null` 또는 `undefined`일 때 `-1`을 반환합니다.
예제
#hostingforum.kr
javascript
// 예제 6: 배열의 요소가 null 또는 undefined일 때
const arr6 = [1, null, 3, undefined, 5];
const index6 = arr6.findIndex((element) => element === 3);
console.log(index6); // 2
댓글목록
등록된 댓글이 없습니다.