JavaScript
자바스크립트 indexOf, findIndex 차이
September Choe
2019. 9. 29. 20:05
728x90
indexOf : 하기 코드의 반환값은 2
const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];
const index = superheroes.indexOf('토르');
console.log(index);
findIndex: 배열 안에 내용물이 객체일때, 그 객체가 배열 안에서 몇번째에 있는지 반환한다.
배열이름.findIndex(인자)
findIndex의 인자는 method이다.
하기 코드의 반환값은 0
const todos = [
{
id : 1,
text : '빨래',
done: true
},
{
id: 2,
text: '숙제',
done: true
},
{
id : 3,
text: '개밥주기',
done: false
}
];
const index2 = todos.findIndex(todo => todo.id === 1);
console.log(index2);
find는 주어진 조건에 해당하는 내용물을 통째로 반환한다.
상기 코드에서 index2 = todos.find(todo => todo.id === 1);이라고 선언하면
콘솔창 출력값은 Object{id: 1, text:'빨래', done: true}가 되는 것이다.
728x90
반응형