자바스크립트 find, findIndex, indexOf

세나정·2023년 4월 17일
0

JavaScript

목록 보기
2/11

find

판별함수를 만족하는 "첫 값"을 반환

arr.find(콜백함수)

콜백함수 : callback(element, index, array)

원하는 요소를 찾자마자 메서드를 종료

const arr = [5, 6, 9, 1, 6, 3, 2, 1, 2, 7, 9, 4, 3];

const find2 = arr.find((element, index, arr) => element === 3);
const find3 = arr.find((e) => e > 8);
const find4 = arr.find((e) => e > 10);

console.log('find2:', find2);
console.log('find3:', find3);
console.log('find4:', find4);

[결과]
find2: 3 (3이 있으니 3을 반환)
find3: 9 (가장 먼저 나온 2번 인덱스)
find4: undefined

findIndex

arr.findIndex(콜백함수)

"해당 인덱스", 없을 시 -1

콜백함수 : callback(element, index, array)

find와 마찬가지로 원하는 요소를 찾으면 메서드 종료

const arr = [5, 6, 9, 1, 6, 3, 2, 1, 2, 7, 9, 4, 3];

const find2 = arr.findIndex((element, index, arr) => element === 3);
const find3 = arr.findIndex((e) => e > 8);
const find4 = arr.findIndex((e) => e > 10);

console.log('findIndex2:', find2);
console.log('findIndex3:', find3);
console.log('findIndex4:', find4);

[결과]
findIndex2: 3
findIndex3: 9	

indexOf

인자로 받은 값을 찾아 맞는 식별자 반환

arr.indexOf(찾을값, 시작할값)

"해당 인덱스", 없을시 -1

원하는 요소를 찾자마자 메서드 종료

const arr = [5, 6, 9, 1, 6, 3, 2, 1, 2, 7, 9, 4, 3];

const find1 = arr.indexOf(1);
const find2 = arr.indexOf(2);
const find3 = arr.indexOf(3);
const find4 = arr.indexOf(4);

console.log('findIndex1:', find1);
console.log('findIndex2:', find2);
console.log('findIndex3:', find3);
console.log('findIndex4:', find4);

[결과]
findIndex1: 3
findIndex2: 6
findIndex3: 5
findIndex4: 11
profile
압도적인 인풋을 넣는다면 불가능한 것은 없다. 🔥

0개의 댓글