for문 vs for-in vs for-of

Calvin Park·2022년 7월 22일
0
for(초기식; 조건식; 증감식){
	실행문
}
for (let i=0; i<10;i++){
	console.log(i)
    //0
    //1
    //2
    .
    .
    .
}

for loop w/o internal expressions
let i =0;
for(;;){
console.log(i++)
if(i==3)break
}

for-in loop

for... in은 for 문과는 전혀 다른 형태의 반복문이다.
for ... in문은 해당 객체의 모든 열거할 수 있는 프로퍼티를 순회할 수 있도록 한다.

for-in loop JSON 오브젝트를 반복할떄
let Obj = {
a:1,
b:2,
};

for(let prop in Obj){
console.log(`${prop}: ${Obj[prop]}`);
}
출력:
//a: 1
//b: 2


class Icon{
  constructor(w, h) {
    this.width = w;
    this.height = h;
  }
}

for(let prop in new Icon(128, 32)) {
	console.log(prop);
}
출력: 
//width
//height

key 값에 접근할 수 있지만, value값에 접근하는방법은 제공을 하지 않는다. Enumerable은, for... in 구문이 이 값이 true로 셋팅되어 속성들만 반복할 수 있다. 이러한 속성들을 열거형 속성이라고 부르며, 객체의 모든 내장 메서드를 비롯해 각종 내장 프로퍼티 같은 비열거형 속성은 반복되지 않는다.

class Icon{
  constructor(w, h) {
    this.width = w;
    this.height = h;
  }
}
let icon = new Icon(128, 32);

// --- Attach a property via prototype
Icon.prototype.myProp1 = 10;

// ---- Attaching a property but explicitly saying it is not enumerable 
Object.defineProperty(icon, "myProp2", {
	enumerable: false
})
// ---- This will not output "myProp2"
for(let prop in icon) {
	console.log(prop);
}
:출력
//width
//height
//myProp1

하지만 Object.defineProperty(icon, "myProp2", {
  enumerable: true,
});
변경을 해주면
//myProp2 <-출력을 볼 수 있다. 

for-of loop

for of은 ES6에서 새로나운 반복형 문법이다. String, Array, TypedArray, Map 그리고 Set을 반복할 수 있다.

//문자열을 looping 하는 것
for (let i of "Character")
console.log(i)
//C
//h
//a
//r
//a
.
.
.
.
Character가 출력 되는 것을 볼 수 가 있다.
//python의 for i in Character와 똑같다.


//let m = new Map():
m.set("a",1).set("b",2);
for (let [i,j] of m)
console.log(`${i} -> ${j}`)
//출력
//a->b
//b->2

// array의 array를 반복할때

for (let [i,j,l] pf [
[4,5,6],
[1,2,3],
])
console.log(i,j,k)
//출력:
//4 5 6
//1 2 3

그럼 언제 어떻게 사용을 해야할까?

  • 만약 값을 꺼내기 위해서 index가 필요하고 또는 index와 관련한 logic이면 for loop을 사용하는 것이 맞는 방법이다.

  • 만약 properties/keys에 접근을 해야하고 order에 상관이 없으면 for - in loop을 사용한다.

  • 만약 반복이 필요한 데이터의 elements(또는 수정이 필요하면) for-of를 사용한다.

상황마다 다 다르겠지만 for-of를 많이 사용할 꺼 같네요.

출처 링크

profile
Personal Velog Note

0개의 댓글