특별한 일상

[JavaScript] Array forEach() 메서드 사용법(배열 forEach()) 본문

IT•개발 끄적/JavaScript

[JavaScript] Array forEach() 메서드 사용법(배열 forEach())

소다맛사탕 2021. 5. 28. 21:10
반응형

안녕하세요. 소다맛사탕입니다.

이번 포스팅에서는 자바스크립트 배열 요소에 대한 지정된 함수를 호출 하는 forEach() 메서드에 대해 간다하게 알아보겠습니다.

 

forEach() 메서드는 배열에서만 사용가능한 메서드

1. 사용법

array.forEach(callback(element, index, arr), thisArg)

callback : 실행할 함수. 즉, function(){}

element : 배열의 현재 요소.

index : 요소의 인덱스.

arr : forEach()가 호출한 배열

thisArg : 콜백을 실행할 동안  this로 사용할 값.

 

2. 예시(for example)

// 배열 선언
var arrVal = [];
arrVal.push("가");
arrVal.push("나");
arrVal.push("다");

// 또는
var arrVal2 = ["라", "마", "바"];

// 배열 forEach() 메서드 사용
arrVal.forEach(function(e, i, ary){
	console.log(e + " :: " + i + " :: " + ary);
});
// 결과
// 가 :: 0 :: 가,나,다
// 나 :: 1 :: 가,나,다
// 다 :: 2 :: 가,나,다

// 또는
arrVal2.forEach(e => console.log(e));
// 결과
// 라 마 바

 

thisArg 사용 예시는 mozilla 문서를 통해서 자세히 알아봤습니다.

function Counter() {
  this.sum = 0
  this.count = 0
}
Counter.prototype.add = function(array) {
  array.forEach(function(entry) {
    this.sum += entry
    ++this.count
  }, this)
  // ^---- 주의
}

const obj = new Counter()
obj.add([2, 5, 9])
obj.count
// 3
obj.sum
// 16

thisArg 매개변수, 즉 this를 forEach()에 제공했기에, callback은 전달받은 this의 값을 자신의 this 값으로 사용할 수 있다.

 

 

※ 배열에서 사용하는 forEach()에 대한 기본개념과 자세한 설명은 하단의 링크를 참고하세요.

참조 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

 

Array.prototype.forEach() - JavaScript | MDN

forEach() 메서드는 주어진 함수를 배열 요소 각각에 대해 실행합니다.

developer.mozilla.org

 

 

 

Comments