dusco01 2023. 11. 28. 21:10
  • 반복문은 특정 명령을 반복해서 수행

ex) console.log(“hi”);
console.log(“hi”);
console.log(“hi”);
console.log(“hi”);
console.log(“hi”);

hi가 5번 출력
비효율적

ex) for (let i = 1; i <= 5; i++)
{
console.log(“hi”);
}

hi가 5번 출력
i가 1부터 5가 될 때까지 hi가 출력되게 해라

반복문은 배열을 순회할 때 매우 유용하다

ex) const arr = [“a”, “b”, “c”];

for(let i = 0; i < arr.length; i++)
{
console.log(arr[i]);
}

a
b
c

반복문은 객체를 순회할 때 매우 유용하다

  • 키만 순회할 때

ex) let person = {
name: “지은”,
age: 23,
tall: 164
};

const personKeys = Object.keys(person);

for(let i = 0; i < personKeys.length; i++)
{
console.log(personKeys[i]);
}

name
age
tall

  • 키와 값 둘 다 순회할 때

ex) let person = {
name: “지은”,
age: 23,
tall: 164
};

const personKeys = Object.keys(person);

for(let i = 0; i < personKeys.length; i++)
{
const curKey = personKeys[i];
const curValue = person[curKey];

console.log('${curKey} : ${curValue}'); 

}

name : 지은
age : 23
tall : 164

  • 값만 순회할 때

ex) let person = {
name: “지은”,
age: 23,
tall: 164
};

const personValues = Object.values(person);

for(let i = 0; i < personValues.length; i++)
{
console.log(personValues[i]);
}

지은
23
164