[Javascript] 배열 - 순회와 탐색

뽕칠이·2024년 6월 25일

1. forEach

마치 반복문처럼 배열 안의 모든 요소를 순회하면서 각각의 요소에 대해 특정 동작을 수행한다.

let arr1 = [1, 2, 3]

arr1.forEach(function(item, idx, arr) {
	console.log(idx, item*2);
});

위 코드 설명

  • 총 3회 호출될 것이다.
  • 첫 번째 호출 -> item = 1, idx = 0, arr = [1, 2, 3]
  • 두 번째 호출 -> item = 2, idx = 1, arr = [1, 2, 3]
  • 세 번째 호출 -> item = 3, idx = 2, arr = [1, 2, 3]
  • console.log 결과
    0 2
    1 4
    2 6

2. includes

배열에 특정 요소가 있는지 확인하는 메서드

let arr2 = [1, 2, 3];

// 요소가 존재할 경우, true 반환
let isIncludes1 = arr2.includes(3);
console.log(isIncludes1);

// 요소가 존재하지 않을 경우, false 반환
let isIncludes2 = arr2.includes(5);
console.log(isIncludes2);

3. indexOf

특정 요소의 인덱스를 앞에서부터 탐색하면서 찾으면 반환하는 메서드

let arr3 = [1, 1, 1, 2, 3];

// 찾으려는 요소가 존재하는 경우
let index = arr3.indexOf(2);
console.log(index);				// 3

// 찾으려는 요소가 여러 개 있는 경우, 가장 앞에 있는 요소의 인덱스를 저장
let oneIndex = arr3.indexOf(1);
console.log(oneIndex);			// 0

// 찾으려는 요소가 존재하지 않는 경우
let noneIndex = arr3.indexOf(10);
console.log(noneIndex);			// -1

4. findIndex

모든 요소를 순회하면서, 콜백함수를 가장 먼저 만족하는 특정 요소의 인덱스를 반환하는 메서드

let arr4 = [1, 2, 3, 4];

const findIndex1 = arr4.findIndex((item) => {
	if (item === 2) return true;
});

console.log(findIndex1);		// 1

const findIndex2 = arr4.findIndex(
  (item) => item % 2 !== 0
);

console.log(findIndex2);		// 0

이 때 주의할 점은 indexOf는 객체의 index를 반환하지 못한다. 이 문제를 해결하기 위해 등장한게 findIndex이다.

let objectArr = [
  {name: "james"},
  {name: "bin"} 
];

// indexOf 메서드로는 객체의 index를 찾을 수 없다.
// -> 얕은 비교를 하기 때문에 참조값을 통해 비교하는 객체를 찾을 수 없는 것이다.
console.log(
  objectArr.indexOf({name: "james"})	// -1을 반환
);

// item.name인 프로퍼티를 통해 비교할 수 있기 때문에 객체를 찾을 수 있다.
console.log(
	objectArr.findIndex(
    	(item) => item.name === "james"	// 0을 반환
    )
)

5. find

findIndex 메서드와 굉장히 유사한데, 차이점은 요소를 그대로 반환하는 것이다.

let arr5 = [
  {name: "james"},
  {name: "bin"}
]

console.log(
	arr5.find((item) => item.name === "james")		// name: "james" 반환
);

0개의 댓글