목차
Math.random() 예제 - (0 ≤ x<1) 랜덤 부동소수
Math.random() 정의
Math.random() 구문
Math.random() 예제 - (1 ≤ x ≤ 10) 랜덤 정수
Math.random() 예제 - (1 ≤ x ≤ 100) 랜덤 정수
Math.random() 예제 - (min ≤ X < max) 함수
Math.random() 예제 - (min ≤ X ≤ max) 함수
Math.random() 예제 - 배열 순서 랜덤 적용
Math.random() 예제 - (0 ≤ x<1) 랜덤 부동소수
<button onclick="homzzang()">클릭</button>
<p id="demo"></p>
<script>
function homzzang() {
var x = Math.random();
document.getElementById("demo").innerHTML = x;
}
</script>
결과보기
Math.random() 정의
0 ≤ x < 1 범위의 부동 소수 형태의 의사 난수 (= 랜덤 숫자) 반환.
(즉, 최소값은 포함 O , 최대값은 포함 x)
1.
암호학 상 안전한 난수 생성 X .
따라서, 보안 코드로 사용 금지.
2.
랜덤 정수 표현 위해서 Math.floor() 객체와 주로 함게 사용.
Math.floor(Math.random() * 10) ; // 0 ~ 9
Math.floor(Math.random() * 11); // 0 ~ 10
Math.floor(Math.random() * 100); // 0 ~ 99
Math.floor(Math.random() * 101); // 0 ~ 100
Math.floor(Math.random() * 10) + 1; // 1 ~ 10
Math.floor(Math.random() * 100) + 1; // 1 ~ 100
3. ECMAScript 1 4. 모든 주요브라우저 지원.
Math.random() 구문
Math.random()
[매개변수]
없음.
[반환값]
(0 ≤ n < 1) 범위의 랜덤 숫자 반환.
Math.random() 예제 - (1 ≤ x ≤ 10) 랜덤 정수
<button onclick="homzzang()">클릭</button>
<p id="demo"></p>
<script>
function homzzang() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demo").innerHTML = x;
}
</script>
결과보기
Math.random() 예제 - (1 ≤ x ≤ 100) 랜덤 정수
<button onclick="homzzang()">클릭</button>
<p id="demo"></p>
<script>
function homzzang() {
var x = document.getElementById("demo")
x.innerHTML = Math.floor((Math.random() * 100) + 1);
}
</script>
결과보기
Math.random() 예제 - (min ≤ X < max) 함수
<button onclick="document.getElementById('demo').innerHTML = homzzang(0,10)" >클릭</button>
<p id="demo"></p>
<script>
function homzzang(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
</script>
결과보기
[예제] - (0 ≤ n < 10) 랜덤 숫자
<button onclick="hz(0, 10)" >클릭</button>
<p id="demo"></p>
<script>
function hz(min,max) {
document.getElementById('demo').innerHTML = homzzang(min, max);
}
function homzzang(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
</script>
결과보기
※ 함수 정의 순서는 상관 없음.
Math.random() 예제 - (min ≤ X ≤ max) 함수
<button onclick="document.getElementById('demo').innerHTML = homzzang(0,10)" >클릭</button>
<p id="demo"></p>
<script>
function homzzang(min, max) {
return Math.floor(Math.random() * (max - min + 1 )) + min;
}
</script>
결과보기
[예제] - (0 ≤ n ≤ 10) 랜덤 숫자
<button onclick="hz(0, 10)" >클릭</button>
<p id="demo"></p>
<script>
function hz(min,max) {
document.getElementById('demo').innerHTML = homzzang(min, max);
}
function homzzang(min, max) {
return Math.floor(Math.random() * (max - min + 1 )) + min;
}
</script>
결과보기
※ 함수 정의 순서는 상관 없음.
Math.random() 예제 - 배열 순서 랜덤 적용
※ JS엔 shuffle() 함수 존재 X (∴ 아래 사용자정의함수 필요.)
function shuffle(array ) {
array .sort (() => Math.random() - 0.5);
}
var nums = [1, 2, 3];
shuffle(nums);
console.log (nums);
강한남v 님 (220217) https://sir.kr/qa/449765
주소 복사
랜덤 이동