Notice
Recent Posts
Recent Comments
«   2025/12   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Today
Total
관리 메뉴

차차로그

JS 반복 foreach, for in, for of 본문

JavaScript

JS 반복 foreach, for in, for of

차차한 2022. 8. 12. 14:16

forEach()

배열.forEach(item, index, array)

배열에서 사용하는 반복문으로 배열의 길이만큼 반복한다.

    const nums = [1,2,3,4,5];
    let numFE = nums.forEach((item, index) => 
        console.log('index : ', index, 'item : ', item)
    );

index :  0 item :  1
index :  1 item :  2
index :  2 item :  3
index :  3 item :  4
index :  4 item :  5

    const obj = {
        1: 'one',
        2: 'two',
        3: 'three',
        4: 'four',
        5: 'five'
    };

    for(var i in obj){
        console.log(i, obj[i]);
    }

객체에서도 사용은 가능하다

for...in

for(변수 in 객체)

객체의 key와 value를 찾을 때 자주 쓰이며 키값의 개수만큼 반복한다.

    const obj = {
        1: 'one',
        2: 'two',
        3: 'three',
        4: 'four',
        5: 'five'
    };

    for(var key in obj){
        console.log(key, obj[key]);
    }

1 one
2 two
3 three
4 four
5 five

	const obj = [1,2,3,4,5];
	for(var key in obj){
        console.log(key, obj[key]);
    }

for..in은 배열에서도 사용이 가능하다!

1 one
2 two
3 three
4 four
5 five

for...of

for(변수 of 객체)

ES6에서 추가된 컬렉션 전용 반복 구문이다.

for of를 사용하기 위해서는 컬렉션 객체가 [Symbol.iterator] 속성을 갖고 있어야 한다.

    const obj = [1,2,3,4,5];

    for(var i of obj){
        console.log(i); // 1 2 3 4 5
    }

요소의 값을 리턴해준다.

만약에 iterator 속성이 없는 값(ex: 객체)을 for of로 반복하려고 하면 오류가 발생하게 된다.

 

'JavaScript' 카테고리의 다른 글

substring(), substr() 비교  (0) 2023.04.18
JS 이벤트, 버블링, 캡처링  (1) 2022.08.31
JS 반복 map(), filter(), reduce()  (0) 2022.08.12
JS 화살표함수  (0) 2022.08.08
JS 배열 합치기  (0) 2022.08.08
Comments