자바스크립트
home
2025 자바스크립트 초급 1500제
home

E0504_개념05_반복문과기억과순서

개념

<script> /* [반복문과 기억과 순서] - 숫자 1부터 10 사이의 랜덤 숫자 4개를 출력한 후, 가장 첫 번째 짝수를 출력하시오. - 단, 전부 홀수일 경우 -1을 출력하시오. */ /* [출력예시] 9 6 4 3 6 [출력예시] 5 9 7 1 -1 */ // [for문] let count = 0; let a = 0; for(let i = 0; i < 4; i++) { let r = Math.floor(Math.random() * 10) + 1; document.write(r, " "); if(count == 0 && r % 2 == 0) { a = r; count = 1; } } document.write("<br>"); if(count == 0) { document.write(-1, "<br>"); } else { document.write(a, "<br>"); } document.write("<br>"); // [while문] let count2 = 0; let a2 = 0; for(let i = 0; i < 4; i++) { let r = Math.floor(Math.random() * 10) + 1; document.write(r, " "); if(count2 == 0 && r % 2 == 0) { a2 = r; count2 = 1; } } document.write("<br>"); if(count2 == 0) { document.write(-1); } else { document.write(a2); } </script>
HTML
복사

영상