본문 바로가기

개발 일기

[Javascript] findIndex() method

findIndex method는 겁나 쉽다

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

const foundAnimal = animals.findIndex(x => {
  return x === 'elephant';
})

const startsWithS = animals.findIndex(x => {
  return x[0] === 's';
})

대충 이렇게 적으면 조건에 맞는 첫번째 값을 반환해 준다.

 

이렇게 겁나 쉬운데 이 글을 적는 이유가 무엇인가 하면

 

findIndex method는 조건에 맞는 값을 찾지 못하면 -1을 반환한다는 것을 기억하기 위함이다...

 

기본적인 문법은 filter랑 똑같다고 생각하면 될 듯! 딱히 어려운 게 없다

 

근데 나는 왜 변수를 x로 적으면 이해가 제일 잘 될까...

나도 변수 이름 아무나 봐도 이해되도록 잘 짓고 싶다ㅋㅋㅋㅋㅋㅋ