- forEach
- map
- indexOf
- findIndex
- find
forEach 함수
는 for문을 대체할 수 있다.
아래와 같은 배열이 있다고 가정해보자.
const fruits = ['apple', 'banana', 'melon', 'orange', 'strawberry'];
이 때 배열 안 모든 원소를 출력하고 싶을 때, for문
을 이용해 출력할 수 있다.
const fruits = ['apple', 'banana', 'melon', 'orange', 'strawberry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
하지만 배열 내장함수인 forEach 함수
로 코드를 더 간결하게 작성할 수 있다.
const fruits = ['apple', 'banana', 'melon', 'orange', 'strawberry'];
fruits.forEach(fruit => {
console.log(fruit);
});
map 함수
는 배열 안에 있는 원소를 변환하고자 할 때 사용된다.원소를 변환해 새 배열을 생성한다.
아래와 같은 배열이 있을 때, 각 원소에 제곱하여 새로운 배열 생성하기.
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const squared = array.map(n => n * n);
console.log(squared);
indexOf
는 원하는 값이 배열의 몇 번째 항목인지 찾아주는 함수이다.
const fruits = ['apple', 'banana', 'melon', 'orange', 'strawberry'];
const index = fruits.indexOf('strawberry');
console.log(index);
결과값은
4
. (배열의 index는 0부터 세기 때문)
배열 안의 값이 객체 혹은 배열일 때는 indexOf 함수로 찾을 수 없기 때문에
findIndex 함수
를 사용한다.
const fruits = [
{ id: 1,
name: 'apple',
color: 'red' },
{ id: 2,
name: 'banana',
color: 'yellow' },
{ id: 3,
name: 'melon',
color: 'green' },
{ id: 4,
name: 'orange',
color: 'orange' },
{ id: 5,
name: 'strawberry',
color: 'red' },
];
const index = fruits.findIndex(fruit => fruit.id === 4);
console.log(index);
결과값은
3
.
find 함수
는 findIndex 함수와 다르게 index 값을 반환하는 게 아닌, 원소 값 자체를 반환한다.
const fruits = [
{ id: 1,
name: 'apple',
color: 'red' },
{ id: 2,
name: 'banana',
color: 'yellow' },
{ id: 3,
name: 'melon',
color: 'green' },
{ id: 4,
name: 'orange',
color: 'orange' },
{ id: 5,
name: 'strawberry',
color: 'red' },
];
const fruit = fruits.find(fruit => fruit.id === 4);
console.log(fruit);
결과값은
{ id: 4, name: 'orange', color: 'orange' }
(원소값이 객체이므로)