Menu
Coddy logo textTech

Find 및 FindIndex 메서드

Coddy JavaScript 여정의 논리 & 흐름 섹션에 포함된 레슨 — 65개 중 58번째.

find() 메서드는 제공된 테스트 함수를 만족하는 배열의 첫 번째 요소를 반환합니다. 만족하는 요소가 없으면 undefined를 반환합니다.

findIndex() 메서드는 비슷하지만 요소 자체 대신 첫 번째로 일치하는 요소의 인덱스를 반환합니다. 일치하는 요소가 없으면 -1을 반환합니다.

기본 구문:

array.find(callback(element[, index[, array]]))
array.findIndex(callback(element[, index[, array]]))

find()를 사용한 간단한 예제:

const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(num => num > 10);
console.log(found);
// 12 (10보다 큰 첫 번째 숫자)

findIndex()를 사용한 동일한 예제입니다:

const numbers = [5, 12, 8, 130, 44];
const foundIndex = numbers.findIndex(num => num > 10);
console.log(foundIndex);
// 1 (10보다 큰 첫 번째 숫자의 인덱스)

배열에서 객체 찾기:

const inventory = [
	{name: 'apples', quantity: 2},
	{name: 'bananas', quantity: 0},
	{name: 'oranges', quantity: 5}
];

// find 사용
const result = inventory.find(item => item.name === 'bananas');
console.log(result); // {name: 'bananas', quantity: 0}

// findIndex 사용
const index = inventory.findIndex(item => item.name === 'bananas');
console.log(index); // 1
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

치트 시트

find() 메서드는 테스트 함수를 만족하는 첫 번째 요소를 반환하며, 만족하는 요소가 없으면 undefined를 반환합니다:

const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(num => num > 10);
console.log(found); // 12

findIndex() 메서드는 일치하는 첫 번째 요소의 인덱스를 반환하며, 일치하는 요소가 없으면 -1을 반환합니다:

const numbers = [5, 12, 8, 130, 44];
const foundIndex = numbers.findIndex(num => num > 10);
console.log(foundIndex); // 1

배열에서 객체 찾기:

const inventory = [
	{name: 'apples', quantity: 2},
	{name: 'bananas', quantity: 0},
	{name: 'oranges', quantity: 5}
];

const result = inventory.find(item => item.name === 'bananas');
// {name: 'bananas', quantity: 0}

const index = inventory.findIndex(item => item.name === 'bananas');
// 1

직접 해보기

이 레슨에는 코드 챌린지가 없습니다.

quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

논리 & 흐름의 모든 레슨