본문 바로가기
Programing/JavaScript

[JavaScript] for 문, for in 문, for of 문

by 미미믹 2022. 2. 23.

Javascript에서 사용하는 for문 정리


for문
가장 기본적인 반복문으로 자바스크립트뿐 아니라 다른 언어에서도 똑같다고 볼 수 있다.

for ([initialization]; [condition]; [final-expression]) { ... }

initialization :: 초기화할 변수. var로 선언할 경우 반복문 밖에서도 사용가능하며 for문에서만 사용할 경우 let으로 선언
condition :: 반복문을 수행할 초기화된 변수의 조건
final-expression :: 반복문 수행 후 수행할 조건
해당 항목들은 필수사항이 아닌 선택사항으로 생략 가능

// initialization 생략
let i = 0;
for(; i<5; i++)
    console.log(`initialization 생략 ${i}`); // 0 ~ 4
    
// condition 생략
for(let i=0; ; i++) {
    console.log(`condition 생략 ${i}`); // 0 ~ 8
    if(i>7) break;
}

// final-expression 생략
for(let i=0; i<9; ) {
    console.log(`final-expression 생략 ${i}`); // 0 ~ 8
    i++
}

 


for ~ in 문
주로 객체의 반복에 사용된다.
객체의 열거가능한(enumerable===true) 속성에 대해 반복한다.
순서를 보장할 수 없기 때문에, Array의 반복에는 사용하지 말라고 안내하고 있다.

for (variable in object) { ... }

variable :: 해당 객체의 열거가능한 속성이름
object :: 반복문을 수행할 객체

Object.prototype.objFunc = function () {};

const obj = {
    apple:'🍎',
    tomatto:'🍅'
}

for(let o in obj)
    console.log(`before :: ${o} = ${obj[o]}`);

// apple 열거가능여부 false 처리
Object.defineProperty(obj, 'apple', {
    enumerable: false
});

for(let o in obj)
    console.log(`after :: ${o} = ${obj[o]}`);
    
    
const arr = ['A', 'B', 'C', 'D', 'E'];
for(let a in arr) {
    console.log(a, arr[a]); // 배열 인덱스, 배열 값
}

for ~ of 문
반복가능한 객체 (Array, Map, Set, String, TypedArray, arguments 객체 등을 포함)의 반복에 사용된다.
ES6에서 추가되었다.

for (variable of iterable) { ... }

variable :: 해당 객체의 값
object :: 반복문을 수행할 객체

let array = [1,2,3];
for(let a of array)
    console.log(a); // 1, 2, 3

let string = 'hello';
for(let s of string)
    console.log(s); // h, e, l, l, o

let map = new Map([['a',1], ['b',2], ['c',3]]);
for(let m of map)
    console.log(m); // ['a', 1], ['b',2], ['c',3]
    
for(let[k,v] of map)
    console.log(`${k}=${v}`); // a=1, b=2, c=3

[참고]
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/for...in
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/for...of

 

728x90

'Programing > JavaScript' 카테고리의 다른 글

[react] npx create-react-app 에러 ENOENT -4058  (0) 2024.03.14
[JavaScript] var, let, const  (0) 2022.02.28