Rylah's Study & Daily Life

find, findIndex 본문

Web Study/Javascript

find, findIndex

Rylah 2022. 4. 15. 15:36
1
2
3
4
5
6
7
8
9
10
11
12
const 조건 = e => e.height >= 180
const 친구들 = [
    {"name" : "Knight""height" : 173},
    {"name" : "Mage""height" : 175},
    {"name" : "Archer""height" : 180},
    {"name" : "Saint""height" : 190},
]
 
const 키큰친구 = 친구들.find(조건)
console.log(키큰친구)
const 키큰친구인덱스 = 친구들.findIndex(조건)
console.log(키큰친구인덱스)
cs

이와 같이 친구들 배열에서 Knight, Mage, Archer, Saint 네 친구가 있다고 가정하자.

여기서 find를 조건으로해서 검색했을 때 가장 먼저 걸리는 Archer를 발견하면 그 값을 log에 찍어주고 종료가 된다.

 

또한 findIndex도 마찬가지로 배열의 2번 인덱스인 Archer를 가리키고 종료된다.

 

만약 발견하지 못한다면 

 

find는 undefined

findIndex는 -1을 결과로 반환한다.

 

  찾은 경우 못찾은 경우
find 그 찾은 항목을 출력 후 종료 undefined
findIndex 찾은 인덱스를 출력 후 종료 -1

'Web Study > Javascript' 카테고리의 다른 글

JS Promise resolve reject  (0) 2022.04.16
JS ES6 Queue  (0) 2022.04.16