| code | |
|---|---|
| Math.random() | 0 <= x < 1 |
| Math.random() * 9 | 0 <= x < 9 |
| Math.floor(Math.random() * 9 +1) | x = {1, 2, 3, 4, 5, 6, 7, 8, 9} |
⚠️ 주의
Math.random()은 완전한 무작위는 아니다. 보안과 관련된 작업(ex. 비밀번호 생성)을 할 때는Math.random()으로 생성된 수를 사용하면 위험하다.
이를 위한window.crypto.getRandomValues()함수가 따로 있다.
🔗 숫자, 수학 method (Number, Math) 복습하러 가기
const $input = document.querySelector('#input');
const $form = document.querySelector('#form');
const $logs = document.querySelector('#logs');
const numbers = []
for(i=0; i < 9; i++){
numbers.push( i + 1 );
}
console.log(numbers); // (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]
💬 for 문을 while 문으로 바꾸는 연습도 꼭 해 보자.
let i = 0;
while(i < 9){
numbers.push(i+1);
i++;
}
console.log(numbers); // (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]
📍 배열과 객체 중 사용하는 기준
- 값만 필요할 땐 배열(Array)
- 각각의 값에 속성 이름을 붙여서 값을 구분해야 할 땐 객체(object)
const answer = [];
for (let i = 0; i < 4; i++){
const index = Math.floor(Math.random()* 9);
answer.push(numbers[index]);
numbers.splice(index, 1);
}
i = 0;
while (i < 4){
const index = Math.floor(Math.random() * 9);
answer.push(numbers[index]);
numbers.splice(index, 1);
i++;
}
const index = Math.floor(Math.random() * 9);
numbers[index] 를 push 하고 numbers 에서 해당 배열 요소를 삭제하더라도 랜덤 숫자의 배열은 줄어 들지 않기 때문에 undefined 가 반환되는 문제가 발생된다.

const index = Math.floor(Math.random() * numbers.length);
numbers.length 를 하게 되면 numbers 의 배열 요소가 하나씩 삭제 되어 적용되므로, 추후 numbers 의 배열 개수를 바꾸더라도 코드를 일일이 고치지 않아도 된다.