JavaScript - Round / Ceil / Floor / Random / Length

🦜 eunhye_k·2022년 3월 17일
1
post-thumbnail

💡 Math란?

수학적인 상수와 함수를 위한 속성과 메서드를 가진 내장 객체

1. Math.round()

  • 주어진 숫자를 반올림한 수와 가장 가까운 정수 값을 반환합니다. -> 반올림
	console.log(Math.round(0.9)); //result: 1
	console.log(Math.round(0.95)); //result: 1
	console.log(Math.round(1.05)); //result: 1

2. Math.ceil()

  • 주어진 숫자보다 크거나 같은 숫자 중 가장 적은 정수 값을 반환합니다. -> 올림
	console.log(Math.ceil(1)); //result: 1
	console.log(Math.ceil(1.9)); //result: 2
	console.log(Math.ceil(1.95)); //result: 2
	console.log(Math.ceil(1.05)); //result: 2

3. Math.floor()

  • 주어진 숫자와 같거나 작은 숫자 중 가장 큰 정수를 반환합니다. -> 내림
	console.log(Math.floor(4)); //result: 4
	console.log(Math.floor(4.9)); //result: 4
	console.log(Math.floor(4.95)); //result: 4
	console.log(Math.floor(4.05)); //result: 4

4. Math.random()

  • 0~1(1은 미포함) 구간에서 부동소수점의 난수를 생성합니다.



👉 Array.length

  • 배열의 길이를 체크하여 정수로 반환합니다.



💡 랜덤으로 명언 호출하기



💡 랜덤으로 이미지 호출하기

//배열에 이미지 파일명 담기
const images = ["bg1.jpg", "bg2.jpg", "bg3.jpg", "bg4.jpg", "bg5.jpg"];

//랜덤 수 곱하기 배열의 수 = 0.XXXXX * 5
//0과 5사이의 숫자를 랜덤으로 추출하고 그 수를 내림하여 정수로 반환 (5 이상의 수는 나오지 않음)
//배열 [0 ,1, 2, 3, 4]중 랜덤으로 나온 수의 값 담기
const chosenImage = images[Math.floor(Math.random() * images.length)];

//img태그 생성
const bgImage = document.createElement("img");

//생성된 img태그 src속성에 img경로 담기
bgImage.src = `img/${chosenImage}`;

//body안에 img태그 추가하기
document.body.appendChild(bgImage);

👋 마치며

스터디 활동을 위해 기록하고 있습니다.
다르거나 추가해야할 내용이 있다면 언제든지 코멘트 남겨주세요 :)

✉ dmsp1234@gmail.com

📍 참고



profile
UI/UX 디자인을 공부하는 퍼블리셔 입니다 (●'◡'●)

0개의 댓글