For...in vs For...of

·2022년 9월 10일
0
post-thumbnail

for(key in obj)

const ellie = {name : 'ellie', age : 4}
ellie.hasjob = true;

for(key in ellie){
console.log(key);
}
// 결과값
name
age
hasJob

오브젝트(객체)에 있는 모든 key를 받아와줌.

for(value of iterable)

const array = [1, 2, 4, 5];
for(value of array){
  console.log(value);
}
//결과
1, 2, 4, 5

배열 안에 있는 모든 값들을 순회하면서 받아옴.

//위의 코드와 동일
const array = [1, 2, 4, 5];
for(let i = 0;, i<array.length ; i++){
  console.log(array[i]);
}
//결과
1, 2, 4, 5

아래의 형식은 예전에 쓰던 방법이지만 코드를 많이 작성해야 해서 권장되는 방법은 아니다.

출처 : 드림코딩

profile
전 이것도 몰라요

0개의 댓글

관련 채용 정보