Javascript findIndex() 메서드

·2024년 6월 12일
0

JavaScript

목록 보기
6/11
post-thumbnail

findIndex();

findIndex()의 동작 방식은 배열에서 주어진 조건을 만족하는 첫 번째 요소의 인덱스를 반환하는 것이다.
만약 조건을 만족하지 못 한다면, findIndex()-1을 반환하게 된다. 이를 통해 조건을 만족하는 요소가 배열에 존재하는지 쉽게 확인할 수 있다.

예시코드

const posts = [
  { postId: 1, title: "Post 1" },
  { postId: 2, title: "Post 2" },
  { postId: 3, title: "Post 3" }
];

const postIdToFind = 2;
const index = posts.findIndex(post => post.postId === postIdToFind);

console.log(index); // 1 (조건을 만족하는 요소를 찾으면 해당 인덱스 반환)

// case2
const postIdToFind2 = 3;
const index2 = posts.findIndex(post => post.postId === postIdToFind);

console.log(index2); // 2 (postId가 있는 배열 인덱스가 2이기 때문임.)

const nonExistentPostId = 4;
const nonExistentIndex = posts.findIndex(post => post.postId === nonExistentPostId);

console.log(nonExistentIndex); // -1 (조건을 만족하는 요소가 없으면 -1 반환)
profile
- 배움에는 끝이 없다.

0개의 댓글