실행결과 미리 보기
목표
목표
1. DOM 요소 개념 복습
DOM 요소 선택 (document.getElementById, document.querySelector)
DOM 요소의 내용 변경 (innerHTML, textContent)
DOM 요소에 스타일 동적 적용 (classList.add, classList.remove)
새로운 DOM 요소 생성 및 추가 (document.createElement, appendChild)
2. 배열의 순회 및 조작 익히기
추가 목표
1. '추첨' 버튼을 클릭 시 1부터 45까지의 숫자가 중복 없이 랜덤 하게 표시됩니다.
2. 추첨으로 나온 숫자는 숫자의 구역에 따라 공 색이 다르게 표시됩니다.
3. '다시' 버튼으로 로또번호를 새로 reset 합니다.
4. '랜덤으로 번호 얻기' 버튼 클릭 시 3가지의 Lotto 번호가 랜덤 하게 표시됩니다.
5. 내 Lotto 번호와 추첨번호가 일치 시 노란색 / 불일치 시 회색으로 공의 색상이 강조됩니다.
6. 색상은 COLORS 배열에서 사용하기
코드리뷰
메인 화면
<div id="check-container" class="container">
<h1 class="title">로또 번호 추첨</h1>
<div class="lotto"></div>
<div class="lotto-btn">
<button id="draw-btn" class="btn">추첨</button>
<button id="reset-btn" class="btn">다시</button>
</div>
</div>
<div id="my-container" class="container">
<h1 class="title">내 Lotto 번호</h1>
<div class="lotto-btn">
<button id="get-btn" class="btn">랜덤으로 번호 얻기</button>
</div>
</div>
오늘의 날짜와 함께 메인 title 제목 갱신
const today = new Date();
const mainTitle = setInterval(function(){
const tdYear = today.getFullYear();
const tdMonth = today.getMonth() +1;
const tdDate = today.getDate();
checkTitle.textContent = `${tdYear}년 ${tdMonth}월 ${tdDate}일 로또 번호 추첨`;
},1000)
- new Date() 함수로 현재 날짜 및 시간 불러오는 객체 생성
- get = 반환 / set 대입
함수명 | 의미 | 설명 | |
getFullYear() | setFullYear() | 년도 | |
getMonth() | setMonth() | 월 | 0~11 > 1월~12월 |
getDate() | setDate() | 일 | |
getDay() | setDay() | 요일 | 0~6 > 일요일 ~ 토요일 |
- serInterval() 함수로 일정한 시간 간격을 두고 반복해서 실행할 수 있다.
위의 코드의 경우는 1000(ms) = 1초 간격으로 실행될 수 있게 했다.
추첨 공의 범위별로 공의 색상 변경
메인 추첨 로또 번호
const LOTTO_COLORS = ['#FBC400','#69C8F2','#FF7272','#AAAAAA','#B0D840', '#fd79a8', '#b2bec3'];
// 숫자 범위별 (10단위로) 공의 색상 변경
const colorIndex = Math.floor(number / 10);
ball.style.backgroundColor = LOTTO_COLORS[colorIndex];
- Math.floor(number / 10); 으로 number의 몫으로 colorIndex 번호 입력
내 로또 번호
// mainLottoNumbers와 myLottoNumbers 배열에서 같은 숫자 확인
const isInMainLotto = mainLottoNumbers.includes(number);
const isInMyLotto = myLottoNumbers.includes(number);
// 같은 숫자가 존재할 경우 배경색을 LOTTO_COLORS[5]로 설정
if (isInMainLotto && isInMyLotto) {
ball.style.backgroundColor = LOTTO_COLORS[5]; // 중복 번호의 색상
}
else {
// 다른 숫자의 경우
ball.style.backgroundColor = LOTTO_COLORS[6]; // 다른 번호의 색상
}
- 메인 추첨공과 일치할 때와 불일치할 때의 색상 변경
- include() 메서드는 문자열에 다른 문자열이 포함되어 있는지 여부를 확인합니다.
1) 포함되어 있다면 true / 포함되어있지 않다면 false를 반환합니다.
2) 대소문자를 구분하여 문자열의 비교합니다.
//예제
let username = 'watnu00'
console.log(username.includes('n')); //true
console.log(username.includes('watnu')); //true
console.log(username.includes('Watnu')); //false
메인 로또 번호 (추첨 버튼 클릭 시)
// 추첨 버튼 클릭 시
drawBtn.addEventListener('click', function(){
while(mainLottoNumbers.length < 6){
//1~45까지 랜덤숫자
let rn = Math.floor(Math.random() * 45) +1;
//중복방지
if(mainLottoNumbers.indexOf(rn) === -1){
mainLottoNumbers.push(rn);
editLottoBall(rn);
}
}
})
- indexOf() 함수는 문자열에서 특정 문자열을 찾습니다.
찾은 문자열이 '첫 번째'로 나타나는 위치 index를 반환합니다. 값이 발견되지 않으면 -1을 return 합니다.
메인 로또 번호 (다시 버튼 클릭 시)
// 다시 버튼 클릭 시
resetBtn.addEventListener('click', function(){
mainLottoNumbers.splice(0,mainLottoNumbers.length);
checkLotto.innerHTML = '';
// 내 로또 번호 배열 초기화
myLottoNumbers.splice(0, myLottoNumbers.length);
// 내 로또 공간 초기화
clearMyLottoContainers();
})
- 다시 버튼 클릭 시, 메인로또번호와 내 로또번호 모두 초기화
// 내 로또 공간 초기화 함수
function clearMyLottoContainers() {
// my-lotto 클래스를 가진 모든 요소를 찾아서 제거
const myLottoContainers = document.querySelectorAll('.my-lotto');
myLottoContainers.forEach(container => {
container.remove();
});
}
- foreach 반복문은 오직 Array 객체에서만 사용가능한 메서드입니다.
배열의 첫 번째부터 마지막까지 반복하면서 item을 꺼낼 수 있습니다.
(forEach() 함수는 반환 값이 항상 undefined입니다. 새로운 배열을 생성하지 않습니다.)
//예제
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
}); //1 2 3 4 5
arr.forEach(function(currentValue[, index[]]) {
// 실행할 코드
}
1. arr : forEach() 함수에 적용할 배열입니다.
2. function : arr 배열의 각 요소에 적용할 때 호출되는 콜백 함수입니다. 이 함수는 세 개의 매개변수를 가질 수 있습니다.
3. currentValue (필수 값): 처리할 현재 요소. 이 매개변수를 통해 현재 요소에 접근할 수 있습니다.
4. index (선택 사항): 처리할 현재 요소의 인덱스. 이 매개변수를 사용하여 현재 요소의 인덱스에 접근할 수 있습니다.
- remove() : 요소를 삭제합니다.
내 로또 번호 (랜덤으로 번호 얻기 버튼 클릭 시)
// 로또 번호 공간 생성 함수
function myLottoTk() {
// 3개의 div 요소 생성
for (let j = 0; j < 3; j++) {
const tk = document.createElement('div');
tk.classList.add('lotto');
tk.classList.add('my-lotto');
myContainer.insertBefore(tk, myLottoBtn);
// 각 div에 6개의 로또 번호 span 추가
for (let i = 0; i < 6; i++) {
let rn;
// 중복되지 않는 랜덤 번호 추출
do {
rn = Math.floor(Math.random() * 45) + 1;
} while (myLottoNumbers.includes(rn));
// 추출된 번호를 내 로또 번호 배열에 추가
myLottoNumbers.push(rn);
// 각 div에 로또 번호 span 추가
showMyNumbers(tk, rn);
}
}
}
- 로또 번호 생성 공간 div 만들기
- 생성된 공간 div를 showMyNumber()로 넘겨주기
// 내 로또 번호 span 추가 함수
function showMyNumbers(container, number) {
const ball = document.createElement('span');
ball.textContent = number;
ball.classList.add('lotto-num');
// mainLottoNumbers와 myLottoNumbers 배열에서 같은 숫자 확인
const isInMainLotto = mainLottoNumbers.includes(number);
const isInMyLotto = myLottoNumbers.includes(number);
// 공 색상 변경
const colorIndex = Math.floor(number / 10);
ball.style.backgroundColor = LOTTO_COLORS[colorIndex];
// 같은 숫자가 존재할 경우 배경색을 LOTTO_COLORS[5]로 설정
if (isInMainLotto && isInMyLotto) {
ball.style.backgroundColor = LOTTO_COLORS[5]; // 중복 번호의 색상
}
else {
// 다른 숫자의 경우
ball.style.backgroundColor = LOTTO_COLORS[6]; // 다른 번호의 색상
}
container.appendChild(ball); // 생성된 div에 로또 번호 span 추가
}
// 랜덤으로 번호 얻기 버튼 클릭 시
getRandomBtn.addEventListener('click', function(){
if (mainLottoNumbers.length !== 0) {
// 내 로또 번호 배열 초기화
myLottoNumbers.splice(0, myLottoNumbers.length);
// 내 로또 공간 초기화
clearMyLottoContainers();
// 내 로또 공간 생성 및 번호 표시
myLottoTk();
} else {
alert('로또를 먼저 추첨해주세요!!');
}
});
- 버튼을 누를 때 기존에 있던 div와 span, 배열 모두 초기화 후 새로 생성 시작
마무리
보완해야 할 점
1. 로또가 당첨 됐을 때의 당첨 문구 추가하기
추후 공부가 필요한 개념
1. DOM 요소 불러오기
2. 함수 function() 작동 원리
'DEVELOPMENT > JavaScript' 카테고리의 다른 글
[JS] 견종 정보 페이지 (9) | 2024.05.03 |
---|---|
[JS] Random Number Game (1) | 2024.04.30 |
[JS] 실습예제 (5) | 2024.04.26 |
[JS] 데이터 타입 (2) | 2024.04.24 |
[JS] 변수 (0) | 2024.04.24 |