Javascript Loops

김진영·2024년 5월 7일
0

구름톤 트레이닝

목록 보기
4/8
post-thumbnail

Loops

자바스크립트에서 루프(Loop)를 사용하면 코드 블록을 여러번 실핼할 수 있게 해줍니다.

루프의 종류

  • for : 코드 블록을 여러번 반복
  • for/in : 캑체의 속성을 따라 반복
  • while : 지정된 조건이 true인 동안 코드 블록을 반복
  • do/while : do/while 루프는 while루프의 변형이다. 이 루프의 조건이 true인지 검사하기 전에 코드 블록을 한 번 실행하고 조건이 true인 동안 루프를 반복합니다.

for

for (statement 1; statement 2; statement 3) {}
// stat 1 = 루프가 시작되기 전에 실행
// stat 2 = 루프 실행을 위한 조건
// stat 3 = 루프 실행된 후마다 실행

for (let i = 0; i < 10; i++) {
  if (i === 3) {
    console.log(3);
    continue;
  }
  if (i === 5) {
    console.log("5 stop the loop");
    break;
  }
  console.log("Number" + i);
}

for/in

// 객체의 속성(property)을 따라 반복합니다.
const user = {
	name: 'Kim',
	province: '경기도',
   	city: '고양시'
}
for(let x in user) {
	console.log(`${x} : ${user[x]}`)
}

while

// 지정된 조건이 true인 동안 코드 블록을 반복
let i = 0
while(i < 10){
	console.log('Number' + i);
  	i++
}

do/while

// do/while 루프는 while 루프의 변형이다.
// 이 루프는 조건이 true인지 검사하기 전에 코드 블록을 한 번 실행
// 그러고 나서 조건이 true인 동안 루프를 반복합니다.

let i = 0;
do {
	console.log('Number' + i)
  	i++
}
while(i < 10)
  
let i = 100;
do {
	console.log('Number' + i)
  i++
}
while(i < 10)

배열을 Loop로 이용해서 컨트롤 하기

// Loop Throuh array
const locations = ['서울', '부산', '경기도', '대구'];

// for
for(let i = 0; i < locations.lenth; i++) {
	console.log(locations[i])	
}
// foreach
locations.forEach(function (location, index, array) {
	console.log(`${index} : ${location}`)
  	console.log(array)
})

// map
locations.map(function (location){
	console.log(location)
})

for vs forEach

  • for루프는 원래 사용되었던 접근 방식이지만 forEach는 배열 요소를 반복하는 새로운 접근방식 입니다.
  • for 루프는 필요한 경우 break문을 사용하여 for 문을 중단할 수 있지많 forEach에서는 이와 같은 작업을 수행할 수 없습니다.
  • for 루프는 원래 await와 함께 작동하지만 forEach는 await와 완벽하게 작동하지 않는다.
  • for 루프를 사용한 성능은 forEach 루프보다 빠르다.

0개의 댓글