Es2020 4강 NumberBaseBall

Ryu·2021년 2월 24일
0

JavaScript

목록 보기
4/5
post-thumbnail

숫자야구

숫자가 카운트될때 1씩 계속 오르게하고 싶다면

check.addEventListener('click', () => { const count = 0

})

이렇게 이벤트 코드 다음에 넣는것이아니라

const count = 0
check.addEventListener('click', () => {

})

이벤트 코드 전에 전역함수로 적어야 한다.

또한 이 count 코드는 1씩 계속 증가하여 변화하기 때문에 const함수가 아닌 let함수를 사용한다.

인풋값이 존재하는가와 인풋값이 4자리를 만족하는가라는 조건문을 하나로 묶을때는 &&를 사용한다.

const value = input.value // 문자열 ex) '3046'
    if(value ) {
        if (value.length === 4){
            
        }

의 코드를

if(value && value.length === 4) {
                    
        }

로 합쳐서 코딩할 수 있다.

boolean 함수를 사용할때
const a, const b 의 변수가 있을때
a and b / a or b
TTT/TTT
TFF/TFT
FTF/FTT
FFF/FFF

따라서 value && value.length === 4 코드는 두조건이 모두 만족해야한다.

자바스크립트는 4자리의 랜덤한 숫자를 한번에 형성 할 수 없기 때문에 1자리씩 랜덤한 숫자를 뽑아주는 함수 4개를 합쳐야 된다.

Math.floor(Math.random()*10)

Math.random() 함수는 0 <= x < 1 사이의 숫자를 랜덤하게 뽑는것이다. 따라서 이 함수가 *10을 하면 0 <= x < 10 의 숫자를 랜덤을 뽑는다.
Math.floor 은 소수점 밑의 숫자를 모두 버리는 내림 함수이다.

const first = Math.floor(Math.random()*10) // 3
const second = Math.floor(Math.random()*10) // 0
const third = Math.floor(Math.random()*10) // 4
const fourth = Math.floor(Math.random()*10) // 6
first + second + third + fourth // 13

이처럼 랜덤한 숫자 4개를 더하면 3046이 아닌 숫자를 모두 더한값 13이 나와버린다.

따라서 이 숫자들을 문자로 바꿔주는 String 함수를 사용한다

const first = String(Math.floor(Math.random()*10)) // 3
const second = String(Math.floor(Math.random()*10)) // 0
const third = String(Math.floor(Math.random()*10)) // 4
const fourth = String(Math.floor(Math.random()*10))// 6
first + second + third + fourth // 3046

하지만 변수로 이런 비슷한 코드들을 지정하고 싶지않다면

let answer = [
    String(Math.floor(Math.random()*10)),
    String(Math.floor(Math.random()*10)),
    String(Math.floor(Math.random()*10)),
    String(Math.floor(Math.random()*10))
];
number(answer.join('')) 

answer[0] + answer[1] + answer[2] + answer [3] 의 값들을 한가지 코드로 줄이기 위하여 join함수를 사용한다.

연산을 해보았을때 join함수가 숫자를 문자열로 변환해주기 때문에 String 함수가 없더라도 상관이 없어진다.

또한 number(answer.join('')) 함수를 구동해보았을때
Number('3046') === 3046
Number('0456') === 456
Number('0032') === 32
로 앞의 0이 사라지는 버그가 발생한다. 따라서 number함수를 제거해야한다.

let answer = [
    Math.floor(Math.random()*10), // 3
    Math.floor(Math.random()*10), // 0
    Math.floor(Math.random()*10), // 4
    Math.floor(Math.random()*10) //6
];
answer.join('') // 3046

이러한 사람의 반복작업을 막기위해 반복문을 작성한다.

모든 반복문엔 조건문이 붙고 조건문이 없는 반복문은 무한반복한다.

let n = 0
while (n <= 3) {
    answer[n] = Math.floor(Math.random() * 10) // n자리 생성
    n = n + 1
}

n = n + 1 은 n += 1 와 n++ 로도 표시할수있다.
n = n - 1 은 n -= 1 와 n--
n = n + 2 는 n += 2
n = n n = 2

별찍기

let n = 4
while (n>=-4){
console.log(' '.repeat(Math.abs(n/2))+'*'.repeat(5-Math.abs(n))+' '.repeat(Math.abs(n/2)))
n = n - 2
}

규칙을 먼저 계산한다. 별 찍히는 규칙을 계산한뒤에 반복문을 이용.

let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let answer = []
let n = 0
while (n <= 3) {
    const index = Math.floor(Math.random() * (10-n))
    answer.push(numbers[index])
    numbers.splice(index,1)
    n = n + 1
}

숫자 배열을 지정하고 랜덤으로 숫자를 뽑은뒤에 중복이 없도록 뽑은 숫자를 제거해준다

배열은 없는 숫자를 선택하도록 명령하면 undefined가 뜬다.

while문 보다 for문이 더 한번에 알아볼수 있기에 for문을 더 많이 쓴다.

let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let answer = []
for (let n = 0; n <= 3; n += 1) {
    const index = Math.floor(Math.random() * (10 - n))
    answer.push(numbers[index])
    numbers.splice(index, 1)

}

for문 (초기화;조건;증가값)
answer.push(numbers[index]):하나의 넘버를 뽑는다.
numbers.splice(index, 1): 뽑은 값을 배열에서 삭제한다.

for of를 이용하여 비교. for of문은 모든객체가 아닌 컬렉션만 반복.

const logs = document.querySelector('#logs')는

에서 logs id를 가진 div를 가져온것인데 이 div안에 무언가를 추가할때(ex. 글자)appendChild를 사용

=> logs.textContent = 'HR'는 기존의 글자를 모두 없앤뒤에 HR를 덮어씌우는 것

=>logs.appendChild(document.createTextNode('HR'))는 기존 글자에 추가하는 것

let strike = 0;
            let ball = 0;
            for (const [aIndex, aNumber] of answer.entries()) {
                for (const [iIndex, iString] of input.value.split('').entries()) {
                    if (aNumber === Number(iString)) {
                        if (aIndex === iIndex) {
                            strike += 1
                        } else {
                            ball += 1
                        }
                    }
                }
            } 

split을 통해 숫자를 문자열로 변환하고
entries함수로 두객체를 비교할 수 있게 변환한다.
ex) [34] === [34]
=>false 가 나오기때문.

profile
쓴다.노트.하는동안.공부

0개의 댓글