JS - randomness

suyeon·2023년 6월 20일
0

Vanilla.js

목록 보기
11/13
post-thumbnail

randomness

...and some more.

Math module

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

⭐️ Math.random()

: 0 ~ 1 사이의 구간에서 부동소숫점(float) 난수(random number)를 반환함.

console.log(Math.random());
// 0.825667262142701

Math.floor()

: "always rounds down and returns the largest integer less than or equal to a given number."

console.log(Math.floor(5.1)); // 5
console.log(Math.floor(5.9)); // 5

Math.ceil()

: "always rounds up and returns the smaller integer greater than or equal to a given number."

Math.round()

: 입력값을 반올림한 수와 가장 가까운 정수 값을 반환함.

console.log(Math.round(3.1)); // 3
console.log(Math.round(3.7)); // 4

Math.trunc()

: 주어진 값의 소수부분을 제거하고 숫자의 정수부분을 반환함.

console.log(Math.trunc(4.98072)); // 4
console.log(Math.trunc(-8.0001)); // 8

  • Example
const quotes = [
  {quote = "Ain't no thing like me, except me!", 
   author = "Rocket",},
];
                
const quote = document.querySelector("#quotes span:first-child");
const author = document.querySelector("#quotes span:last-child");

const randomQuote = quotes[Math.floor(Math.random() * quotes.length)];

quote.innerText = randomQuote.quote;
author.innerText = randomQuote.author;

참고

profile
coding & others

0개의 댓글