반영훈/웹 개발
[JS]배열 내장함수 indexOf, findIndex, find
Banda
2020. 8. 11. 16:41
indexOf
indexOf는 원하는 항목이 몇번째 '원소'인지 찾아주는 함수입니다.
(배열 안에 있는 값이 숫자, 문자열, 불리언 일 때)
예를 들어서 다음과 같은 배열이 있을 때
const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];
토르가 몇번째 항목인지 찾으려면 아래와 같이 입력하면 됨
const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];
const index = superheroes.indexOf('토르');
console.log(index);
findIndex
(배열안에 있는 값이 객체, 배열 일 때)
const todos = [
{
id: 1,
text: '자바스크립트 입문',
done: true
},
{
id: 2,
text: '함수 배우기',
done: true
},
{
id: 3,
text: '객체와 배열 배우기',
done: true
},
{
id: 4,
text: '배열 내장함수 배우기',
done: false
}
];
만약 여기서 id가 3인 객체가 몇번째인지 찾으려면, findIndex 함수에 검사조건을 반환하는 함수를 넣어서 찾을 수 있음.
const todos = [
{
id: 1,
text: '자바스크립트 입문',
done: true
},
{
id: 2,
text: '함수 배우기',
done: true
},
{
id: 3,
text: '객체와 배열 배우기',
done: true
},
{
id: 4,
text: '배열 내장함수 배우기',
done: false
}
];
const index = todos.findIndex(todo => todo.id === 3);
console.log(index);
find
findIndex는 찾아낸 값이 몇번째 인지 알아내지만 find는 찾아낸 값 자체를 반환합니다.
const todos = [
{
id: 1,
text: '자바스크립트 입문',
done: true
},
{
id: 2,
text: '함수 배우기',
done: true
},
{
id: 3,
text: '객체와 배열 배우기',
done: true
},
{
id: 4,
text: '배열 내장함수 배우기',
done: false
}
];
const todo = todos.find(todo => todo.id === 3);
console.log(todo);