난수 생성하기 (랜덤 숫자, Random Number)
안녕하세요 TriplexLab입니다.
오늘은 이미의 숫자를(랜덤숫자 배열)을 받아 배열에 누적 시키는 방법에 관해서 살펴 보도록 하겠습니다.
아래 코드를 보면 myHistory, otherHistory 각 배열에 랜덤의 숫자들이 클릭 할때마다 누적되는 모습을 확인 할수 있습니다.
<button class ="add" > 누적</button >
<script>
(function ( ){
const myHistory = new Array ();
const otherHistory = new Array ();
function random (n ) {
return Math .ceil (Math .random () * n);
};
function arrNumber ( ) {
const nextNum = random (6 );
const nextOtherNum = random (6 );
myHistory.push (nextNum);
otherHistory.push (nextOtherNum);
};
document .querySelector ('.add' ).addEventListener ('click' , function ( ){
arrNumber ();
console .log (myHistory)
console .log (otherHistory)
});
})();
</script>
여기서 중요한 사실을 이야기 한다면 위 코드는 새로운 배열들의 원소값들이 변하는것이지, 참조하는 주소값은 변하지 않고 그대로 입니다.
테스트 코드 👇
실제로 myHistory변수값을 prev변수에 넣고, myHistory.push()다음에 console.log(prev === myHistory)를 비교해보면 결과는 true가 나옵니다. (이것은 원소들이 같다고 true나오는것이 아닌, 참조하고 있는 주소값이 같아서 true가 나온것 입니다.)
function arrNumber ( ) {
const nextNum = random (6 );
const nextOtherNum = random (6 );
const prev = myHistory;
myHistory.push (nextNum);
console .log (prev === myHistory)
otherHistory.push (nextOtherNum);
};
위 코드를 개선한다면 다음과 같이 할수 있습니다.
<script>
(function ( ){
const myHistory = new Array ();
const otherHistory = new Array ();
let result;
let otherResult;
function random (n ) {
return Math .ceil (Math .random () * n);
};
function arrNumber ( ) {
const nextNum = random (6 );
const nextOtherNum = random (6 );
myHistory.push (nextNum);
otherHistory.push (nextOtherNum);
result = myHistory.reduce (function (acc, cur ){
acc.push (cur);
return acc;
},[]);
otherResult = otherHistory.reduce (function (acc, cur ){
acc.push (cur);
return acc;
},[]);
};
document .querySelector ('.add' ).addEventListener ('click' , function ( ){
arrNumber ();
console .log (result === myHistory)
console .log (result)
console .log (otherResult)
});
})();
</script>
실행 결과) 👇
클릭할때 마다 렌덤의 숫자를 새로운 배열로 받아 출력합니다.