TIL #9

김태훈·2023년 2월 15일
0

TIL

목록 보기
8/35

find, findIndex, indexOf

자바스크립트 Array.prototype이고, 배열에서 원하는 값 또는 식별자를 찾아내는 메서드이며, 배열을 순차 반복한다는 공통점이 있다.

find

arr.find(callback)
판별 함수를 만족하는 첫 요소를 반환한다.

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// Expected output: 12

findIndex

arr.findIndex(callback)
원하는 요소의 식별자를 찾는다.

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// Expected output: 3

indexOf

arr.indexOf(search, fromIndex)
원하는 요소의 식별자를 찾는다.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// Expected output: 1

// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4

console.log(beasts.indexOf('giraffe'));
// Expected output: -1

차이점을 인지하고 적절한 상황에 맞춰서 쓰자.

profile
개발자(진)

0개의 댓글