윤쨩이의 개발 블로그

09 [ 배열 메소드 _find() / findIndex() : 배열 요소 검색하기 ] 본문

자바스크립트 메소드/배열 메소드

09 [ 배열 메소드 _find() / findIndex() : 배열 요소 검색하기 ]

윤쨩이 2021. 10. 16. 11:25
find() :  배열에 특정 요소가 있는지 탐색한다.
findIndex() : 배열에 특정 요소가 있는지 탐색하고 그 요소가 몇번째 인덱스에 있는 지 값을 출력한다.

 

01) find()

구문

arr.find(callback[, thisArg])

- callback

: 배열의 각 값에 대해 실행할 함수

- thisArg

: 선택 항목. 콜백이 호출될 때 this로 사용할 객체.

 

 

예제를 통해 알아보자.

const arr = ["apple","watermelone","banana","orange","peach"];

console.log(arr.find(fruit => (fruit == "apple")));		//apple

console.log(arr.find(fruit => (fruit == "banana")))		//banana

console.log(arr.find(fruit => (fruit == "a")))

 

02) findIndex() 

const arr = ["apple","watermelone","banana","orange","peach"];

console.log(arr.findIndex(fruit => (fruit == "apple")));	//0
console.log(arr.findIndex(fruit => (fruit == "banana")));	//2

"apple"과 "banana"의 인덱스 번호를  찾는 것을 확인할 수 있다.

 

 

 

참고 :

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/find

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

 

 

Comments