[Javascript] 배열요소 순회 및 탐색 메서드
forEach메서드
모든 요소를 순회하면서, 각각의 요소에 특정 동작을 수행시키는 메서드
배열이름.forEach(콜백함수 (현재요소값, 현재 반복 카운트, 전체 배열의 값) {});
let arr1 = [1, 2, 3];
arr1.forEach(function (item, idx, arr) {
console.log(idx, item * 2);
});
→결괏값:
0 2
1 4
2 6
includes메서드
배열에 특정 요소가 있는지 학인하는 메서드
배열이름.includes(확인할 요소);
let arr2 = ['red', 'blue', 'green'];
let isIncludes = arr2.includes('red');
console.log(isIncludes);
→결괏값: true
존재하지 않는 요소를 찾는다면
let isIncludes2 = arr2.includes(30);
console.log(isIncludes2);
→결괏값: false
indexOf메서드
특정 요소의 인덱스를 찾아서 반환하는 메서드
배열이름.indexOf(확인할 요소);
let arr3 = ['red', 'blue', 'green'];
let index = arr3.indexOf('red');
console.log(index);
→결괏값: 0
만약에 배열의 요소 내용이 다 같을 때는
let arr3_ = [ 'red', 'red', 'red'];
let index_ = arr3_.indexOf('red');
console.log(index_);
→결괏값: 0 ( indexOf는 맨 앞부터 수행하기 때문에 )
존재하지 않는 요소를 찾는다면
let index__ = arr3.indexOf(4);
console.log(index__);
→결괏값: -1
findIndex메서드
모든 요소를 순회하면서, 콜백함수를 만족하는(콜백함수가 참) 특정 요소의 인덱스를 찾아서 반환하는 메서드
배열이름.findIndex(콜백함수() {});
let arr4 = ['red', 'blue', 'green'];
const findedIndex = arr4.findIndex((item) => {
if (item === 'blue') return true;
});
console.log( findedIndex );
→ 결괏값: 1
이때 화살표 함수 더 간단하게 표현 가능
const findedIndex = arr4.findIndex((item) => item === 'blue');
배열에 존재하지 않는 요소 일 때는
const findedIndex_ = arr4.findIndex((item) => item === 'black');
console.log(findedIndex_);
→ 결괏값: -1
indexOf가 있는데 굳이 findIndex 쓰는 이유는?
indexOf는 얕은 비교를 해 요소가 객체타입일 때는 찾아내지 못하기 때문에
findIndex는 조건식만 잘 맞추면 복잡한 객체타입도 잘 찾아냄
find메서드
모든 요소를 순회하면서, 콜백함수를 만족하는(콜백함수가 참) 특정 요소를 그대로 반환하는 메서드
배열이름.find(콜백함수() {});
let arr5 = [
{color : 'red'},
{color : 'blue'},
{color : 'green'}
];
const finded = arr5.find((item) => item.color === "red");
console.log(finded);
→ 결괏값: {color : 'red'}