LOOP

99PERCENT·2022년 2월 21일
0

JavaScript

목록 보기
8/12

Loop 종류

	for loop
	while loop
	for…of loop
	for…in loop

For Loop Syntax(From MDN)

	for (
		[initalExpression];			// 초기표현식
		[condition];				// 조건
		[incrementExpression] 		// 증감표현식(감소, 증가, 곱셈, 나눗셈)
	) 

For Loop

	Syntax
	for(초기표현식; 불리언표현식; 증감표현식){ }
	예시
	for(let i=1; i<=10; i++;){
		console.log(i);
	}
		

Infinite Loop —> Computer Run Out

	루프가 멈추지 않으면 Javascript가 가진 메모리를 모두 소진하게 된다.
	for(let i = 20; i>=0; i++){
		console.log(i);
	}

Looping over Arrays (배열 루프)

	예시
	const animals = [‘tiger’, ‘lion’, ‘dog’];

		
	for(let i=0; i < animals.length; i++){
		console.log(i, animals[i]);
	}
	// 0 ‘tiger’
	// 1 ‘lion’		
	// 2 ‘dog’ 

Nested Loops (중첩 루프)

	기초
		const size =LMSfor(let i=0; i<=4; i++){
   			console.log("Outer:", i);
         
   			for(let j=0; j<str.length; j++){
       			console.log('   Inner:', str[j]);
   			}
		}
	응용 : 일렬로 세우기
		const seatingChart = [ 
        	 ['Kevin','Alex','Marry'], 	
        	 ['Son','Kane','Moura','Dele'],
        	 ['Sandro','Tom','De','Tonny','Max']
       	]; 

		for(let i=0; i<seatingChart.length; i++){
		    for(let j=0; j<seatingChart[i].length; j++){
     		  console.log(seatingChart[i][j]);
		    }
		}			
	혹은
		for(let i=0; i<seatingChart.length; i++){
			const row = seatingChart[i];for(let j=0; j < row.length; j++){
				
             	console.log(row[j]);
			}
		}

While Loop

		while(boolean){
			execution
			incrementExpression
		}
	예시
		let num = 0;
		
		while(num < 10) {
			console.log(num);
			num++
		}	
	응용 : 비밀번호 입력
		const SECRET = “BabyHippo”;

		let guess = prompt(“Enter your password.);
		while(guess !== SECRET){
			let guess = prompt(“Enter your password.);
		}
	결론 :
    	사람들은 for loop를 더 선호한다. 
    	“반복횟수가 정해져있지 않을 때” while 루프가 더 유용하다.
	

While Loop Break Keywords

	예시1 : 난수와 난수끼리 서로 맞출때까지 반복되는 게임
		let targetNum = Math.floor(Math.random()*10);
		let guess = Math.floor(Math.random()*10);

		while(true){
  		    guess = Math.floor(Math.random()*10);
		    console.log(`시작`);
		    if(guess===targetNum){
     			console.log(`Congrats! Guessed: ${guess} & target: ${targetNum}`);
   			   	break;
 		    } else {
		        console.log(`Fail! Guessed: ${guess} & target: ${targetNum}`);
		    }
		}
	예시2 : 사용자 입력값과 컴퓨터 난수 값 맞추기 게임
		let input = parseInt(prompt("Guess one Number!"));
		let randomNum = Math.floor(Math.random()*10);

		while(true){
		    let randomNum = Math.floor(Math.random()*10);
		    input = parseInt(prompt("Guess one Number!"));

 		   if(input === randomNum){
      		 	 console.log(`Congrats! It's the same number. You: ${input}, Me: ${randomNum}`);
     		 	 break;
		    } else {
		        console.log(`Fail... You: ${input}, Me: ${randomNum}`);
		    }
		}

FOR…OF

	배열 속 값들을 알아서 나열해준다.
		for(let new-variable of utterable){
			statement
		}
	for-of 전
		const sellingDrinks = [‘hotsix’, ‘redbull’, ‘milkies’, ‘pokari’, ‘coke’, ‘soda’];

		for(let i = 0; i < drinks.length; i++){
			console.log(`Finding what you can drinks… ${drinks[i]}`);
		}
	for-of 후
		const drinks = [‘hotsix’, ‘redbull’, ‘milkies’, ‘pokari’, ‘coke’, ‘soda’];
		
		for(let selling of sellingDrinks){
			console.log(`Finding what you can drinks… ${selling);
		}
	2)for-of 전 
		const seatingChart = [ 
          ['Kevin','Alex','Marry'], 
          ['Son','Kane','Moura','Dele'],
          ['Sandro','Tom','De','Tonny','Max'] 
        ]; 

		for(let i=0; i<seatingChart.length; i++){
		    for(let j=0; j<seatingChart[i].length; j++){
      		  console.log(seatingChart[i][j]);
		    }
		}	
	2)for-of 후
		const seatingChart = [ 
          ['Kevin','Alex','Marry'], 
          ['Son','Kane','Moura','Dele'],
          ['Sandro','Tom','De','Tonny','Max'] 
        ]; 

		for(let row of seatingChart){
			for(let student of row){
				console.log(student);
			}
		}
	결론 : 
		배열을 반복해서 사용하는데, 인덱스에 신경쓸 필요가 없을 때 사용하면 굉장히 좋다. 
		하지만, 인덱스가 꼭 필요할 땐 일반적인 for-loop를 사용해야 된다.
		for…of는 배열과 굉장히 많이 쓰이고, 문자열처럼 Javascript에서 반복 가능한 객체로 인식되는 것에도 사용이 가능하다. 

객체 루프

	키-값 쌍의 객체 리터럴은 객체는 맞지만, 반복 가능한 객체로 인식되지 않는다.
	
	1) for…in 루프를 통해 반복할 수 있다.
		
	2) 배열로 만들어버려서 반복할 수도 있다.
		Object.keys(객체변수명);	—> 객체의 키 배열로 반환
		Object.values(객체변수명);	—> 객체의 값 배열로 반환
		Object.entries(객체변수명); 	—> 객체의 키-값쌍 배열로 반환		
		// 예시 : 골 합계 계산
		const tottenhamScores = {
			son : 12,
			kane : 16,
			moura : 6,
			dele : 2,
			winks : 1,
			davies: 1
		}
		
		let total = 0;
		for(let scores of Object.values(tottenhamScores)){
			total += scores;	
		}
	예시2 : 골 평균 계산
		let total = 0;
		let allPlayers = Object.values(tottenhamScores);

		for(let scores of allPlayers){
 		      total += scores;
		}
		console.log(`Spurs scored ${total} goals last season!`);
		console.log(`Spurs' each Players scored ${Math.floor(total/allPlayers.length)} goals last season!`);
	결론) 객체에서의 반복은 배열에서의 반복보다 매우 흔치않다. 하지만 반복을 해야한다면 for-in 혹은 배열로 만들어서 처리할 수 있다.

활용 : To Do List

          let input = prompt('What you want at ToDo?');
          const todo = [];

          while(input !== 'quit' && input !== 'q'){
               if(input === 'list'){
                      console.log('********To Do*********');
                       for(let i = 0; i<todo.length; i++){
                          console.log(`${i}: ${todo[i]}`);
                   }
                  console.log('**********************');
                } 
       			else if(input === 'new'){
                      const newToDo = prompt('What is your new ToDo?');
                      todo.push(newToDo);
                      console.log(`${newToDo} is added to the list!`);
                }
                else if(input === 'delete'){
                      const deleteToDo = prompt('Which toDo "index number" you want to delete?');
                      console.log(`${todo[deleteToDo]} is gonna be delete...`);
                      todo.splice(deleteToDo, 1);
                }
                input = prompt('What you want at ToDo?');
          }

          console.log('Quit ToDo List.');
profile
99 ~ 100

0개의 댓글