-
자바스크립트 - Math 함수프로그래밍/JavaScript 자바스크립트 2021. 9. 28.반응형<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><link rel="icon" href="data:;base64,iVBORw0KGgo="><script type="text/javascript">var s;s = Math.PI; // 원주율console.log(s);s = Math.round(10.2); // 숫자에 가장 가까운 정수console.log(s); // 10s = Math.round(10.5); // 숫자에 가장 가까운 정수console.log(s); // 11s = Math.ceil(10.1); // 인수보다 크거나 같은 수 중에서 가장 작은 정수console.log(s); // 11s = Math.floor(10.2); // 인수보다 작거나 같은 수 중에서 가장 큰 정수console.log(s); // 10s = 10/4;console.log(s); // 2.5s = Math.floor(10 / 4);console.log(s); // 2s = Math.random(); // 0 <= 난수 < 1console.log(s);s = Math.floor(Math.random()*10);console.log(s); // 0 ~ 9 사이 난수s = Math.pow(2, 10); // 2의 10승console.log(s);</script></head><body><h3>내장 객체 - Math</h3></body></html>
내장 객체로써 Math 함수는 말 그대로 여러 수학에 관련된 함수들이 있다.
대표적인게 random() 함수로 난수 표현할때 사용
floor 함수도 자주 사용된다. (인수 보다 작거나 같은 수 중에서 가장 큰 정수를 반환)
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><link rel="icon" href="data:;base64,iVBORw0KGgo="><style type="text/css">#box {width: 300px; height: 300px; border: 5px solid gray;margin: 30px auto;}</style><script type="text/javascript">function bg() {var r = Math.floor( Math.random() * 256 ); // 0~255var g = Math.floor( Math.random() * 256 );var b = Math.floor( Math.random() * 256 );var layout = document.getElementById("box");layout.style.backgroundColor = "rgb("+r+","+g+","+b+")";setTimeout("bg()", 500);}window.onload = function() {bg();}</script></head><body><div id="box"></div></body></html>난수를 이용해서 rgb 값을 랜덤으로 주고
이걸 활용해서 배경색을 0.5초 마다 갱신 할 수 있다.
반응형'프로그래밍 > JavaScript 자바스크립트' 카테고리의 다른 글
자바스크립트 - 배열 / 객체 (1) (0) 2021.09.30 자바스크립트 - 달력 (0) 2021.09.28 자바스크립트 - 시간 관련 함수 (Date) (0) 2021.09.28 자바스크립트 - 문자열 활용 (0) 2021.09.27 자바스크립트 - 함수 만들기 (0) 2021.09.27