TIL-16 JS로 숫자야구를 만들어보자!
16570 단어 숫자야구JavaScriptJavaScript
유튜브 제로초님 강의를 보면서 코딩을 하는데
한번 쭉 보고 혼자 만들다가 막히는 부분을 보는 형식으로 하는데
사용자가 입력한 숫자와 정답을 비교하는 부분이 조금 어려웠다.
그리고 함수 리턴 값을 true로 입력해서 if 문에 넣는 것도 이렇게 응용할 수 있구나 배웠다.
<body>
<form class="form">
<input class="input">
<input type="submit" class="submit">
</form>
<div class="log"></div>
<script>
let $input = document.querySelector('.input')
let $submit = document.querySelector('.submit')
let number = [];
for (let n = 1; n < 10; n++) {
number.push(n)
}
let answer =[];
for (let n = 0; n < 4; n++) {
let random = Math.floor(Math.random() * number.length)
answer.push(number[random])
number.splice(random,1)
}
let tries = [];
function cheak(input) {
if (input.length !== 4 ){
return alert('4자리를 입력해주세요.');
}
if (new Set(input).size !== 4){
return alert('중복된 숫자가 있습니다.');
}
if (tries.includes(input)){
return alert('이미 시도한 값입니다.');
}
return true;
}
document.querySelector('.form').addEventListener('submit', () => {
event.preventDefault()
let strike = 0
let ball = 0
for (i = 0; i < 4; i++){
$input.value.indexOf(answer[i])
if($input.value.indexOf(answer[i]) > -1){
if($input.value.indexOf(answer[i]) === i){
strike += 1;
}
else {
ball += 1;
}
}
}
if (cheak($input.value)){
tries.push($input.value)
document.querySelector('div').innerHTML = document.querySelector('div').innerHTML + $input.value + ' strike : ' + strike + ' ball : ' + ball + '<br>'
}
if (answer.join('') === $input.value){
document.querySelector('div').innerHTML = '홈런입니다'
return
}
if (tries.length >= 9){
document.querySelector('div').innerHTML = '실패입니다'
return
}
})
</script>
</body>
알게 된 점
1. event.preventDefault()
예시)
1. <a>
를 눌렀을때 href 링크로 이동하지 않게 된다.
2. <form>
안에 submit 역할을 하는 버튼을 눌러도 웹페이지가 새로고침 X 하지만 (submit은 작동됨)
2. new Set(input).size
new Set() 중복값을 제거해준다.
.size 배열의 Length 와 같은 역할을 한다.
참고자료
https://www.youtube.com/watch?v=MlANtfGIlzI&list=PLcqDmjxt30RvEEN6eUCcSrrH-hKjCT4wt&index=48
Author And Source
이 문제에 관하여(TIL-16 JS로 숫자야구를 만들어보자!), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@ssxst31/TIL-16-JS로-숫자야구를-해보자저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)