728x90

자바스크립트(ES6)의 다양한 for 문 : forEach 문, for ... in 문, for ... of 문

들어가며

  • 자바스크립트 ES6에 있는 다양한 종류의 for 문에 대해 알아보자.
  • 자바스크립트에는 for 문, forEach 문, for ... in 문, for ... of 문이 있다. (ES6 기준)

 

① for 문

for (초깃값; 조건; 증가식) { ... }

 

  • 조건에 들어가는 값이 일정하게 커지면서 명령을 반복 실행할 때 편리하다.
  • 몇 번 반복했는지 기록하기 위해 카운터를 사용하고, for 문의 첫 번째 항에서 카운터 변수를 지정한다.

 

예제 코드
const seasons = ["Spring", "Summer", "Fall", "Winter"];

for (let i = 0; i < seasons.length; i++) {
    document.write(`${seasons[i]}, `);
}

 

위의 코드에서 백틱(Backtick, `)으로 나타낸 부분은 템플릿 리터럴을 의미한다.
템플릿 리터럴(Template Literal)은 문자열과 변수, 식을 섞어서 하나의 문자열을 만드는 표현 형식이다.
(템플릿 리터럴이 등장하기 전에는 문자열 부분을 큰 따옴표(")로 묶은 후에 연결 연산자인 +를 사용해서 식이나 변수와 연결했다.)
파이썬에서도 자바스크립트의 템플릿 리터럴과 비슷하게 F-string을 사용할 수 있다. (season = f"{seasons[i]}")

 

② forEach문

배열명.forEach(콜백 함수) { ... }

 

  • 단순히 배열 요소만 가져와서 보여준다면 for 문forEach 문 사이에는 큰 차이가 없다.
  • 하지만, 프로그램 중에서 배열의 길이가 바뀌어 정확하게 배열의 크기를 알 수 없거나 배열의 요소를 가져와서 함수를 실행해야 할 때 @forEach@ 문을 사용하는 것이 더 편리하다.
const seasons = ["Spring", "Summer", "Fall", "Winter"];

seasons.forEach(function(season) {
    document.write(`${season}, `);
});

 

콜백 함수(Callback Function)란, 다른 함수의 인수로 사용할 수 있는 함수를 의미한다. 위의 예제 코드에서 function(season) { ... } 부분이 콜백 함수에 해당한다.

 

③ for ... in 문

for (변수 in 객체) { ... }

 

  • 배열에서만 반복되는 반복문이 forEach 문이라면, for ... in 문반복해서 객체의 값을 가져와서 처리할 수 있게 해준다.
  • for ... in 문객체의 키(Key)만 가져올 수 있으므로, 해당 키의 값에 접근하려면 대괄호(@[ ]@)를 사용한다.
const product = {
    name : "Peaceminusone",
    releaseDate : "2023-02-03",
    size : "XL",
    sold : true
};

for (key in product) {
    document.write(`${key} : ${product[key]} <br>`);
}

 

④ for ... of 문

for (변수 of 객체) { ... }

 

  • 문자열이나 배열과 같은 반복 가능한(Iterable) 자료에서 사용하는 반복문
  • 위에서 forEach 문으로 사용해서 작성했던 예제 코드를 다음과 같이 for ... of 문으로도 작성할 수 있다.
const seasons = ["Spring", "Summer", "Fall", "Winter"];

// seasons에 season이 있는 동안 계속 반복
for (season of seasons) {
    document.write(`${season}, `);
};

 

참고 사이트

 

for - JavaScript | MDN

The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.

developer.mozilla.org

 

Template literals (Template strings) - JavaScript | MDN

Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.

developer.mozilla.org

 

PEP 498 – Literal String Interpolation | peps.python.org

PEP 498 – Literal String Interpolation Author: Eric V. Smith Status: Final Type: Standards Track Created: 01-Aug-2015 Python-Version: 3.6 Post-History: 07-Aug-2015, 30-Aug-2015, 04-Sep-2015, 19-Sep-2015, 06-Nov-2016 Resolution: Python-Dev message Table o

peps.python.org

 

728x90