Javascript/Javascript
[Javascript] 배열 내장 함수 정리(indexOf, findIndex, find)
금요일인줄
2020. 8. 14. 13:01
728x90
반응형

indexOf는 내가 원하는 텍스트 위치를 알려준다.
const animals = ['호랑이', '사자', '사슴', '토끼', '거북이'];
const index = animals.indexOf('사자');
console.log('사자의 위치는 : ' + index);

하지만 indexOf의 경우 대상이 객체이거나, 특정 대상의 값으로 찾는 것이 아닌 어떤 조건을 가지고 찾을 경우 값을 찾을 기 어렵다.
이럴 때 findIndex를 사용한다.
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("todos의 id가 3인 위치는 " + index);

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);

728x90
반응형