JavaScript/JQuery
[JQuery] 간단하게 랜덤 숫자 생성하기
이나피스
2023. 6. 7. 15:01
반응형
랜덤숫자를 생성할때 Math.random()를 사용하게 되면 0~1 사이의 랜덤값이 나오게 된다
예제에서도 0.6126455291899326의 숫자가 생성되는데 소수점 이하의 숫자에서 n개의 숫자를 가져오기위해
substr(beginIndex, length) 로 가져오면 간단하게 랜덤 n개의 숫자를 가져올수 있다
$(document).ready(function(){
createOtpNumber(6);
});
function createOtpNumber(n){
let otp = Math.random();
console.log("Math.random() :", otp);
console.log("Math.random().toString().substr(2, n) :", otp.Math.random().toString().substr(2, n));
}
참고자료
반응형