JS. 로또 번호 추첨기

Dana·2021년 12월 13일
0

JavaScript

목록 보기
4/5
post-thumbnail
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>로또 번호 추첨기</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>로또 번호 추첨기</h1>
    <script>
        var lotto = [];
        while (lotto.length < 6) {
            var num = parseInt(Math.random() * 45 + 1);
            if (lotto.indexOf(num) == -1) {
                lotto.push(num);
            }
        }
        lotto.sort((a,b)=>a-b);
        document.write("<div class='ball ball1'>" + lotto[0] + "</div>");
        document.write("<div class='ball ball2'>" + lotto[1] + "</div>");
        document.write("<div class='ball ball3'>" + lotto[2] + "</div>");
        document.write("<div class='ball ball4'>" + lotto[3] + "</div>");
        document.write("<div class='ball ball5'>" + lotto[4] + "</div>");
        document.write("<div class='ball ball6'>" + lotto[5] + "</div>");
    </script>
</body>
</html>

사용한 함수

while (조건) { 반복하려는 코드}
값이 6개가 되도록 반복
Math.random()
1이상 46미만의 무작위의 값을 추출
parseInt()
소수점을 버리고 정수를 반환
indexOf()
배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환
번호 중복을 막기위해 사용함
push()
중복하지 않으면 값을 넣어줌
lotto.sort((a,b)=>a-b);
오름차순으로 정렬

profile
웹개발

0개의 댓글