QUOTES

stayby94·2023년 6월 26일

JS문법

목록 보기
1/15

10개의 명언을 랜덤으로 내 website에 띄우고자 할때 사용하는 방법에 대한 내용.

먼저 10개의 명언을 array로 묶었을때 0번~9번까지 숫자를 주는 function이 필요한데

이때 Math Moudule을 사용함. javascript에 기본적으로 포함되어 있는 기능임.

Math.random()  --> 0부터 1사이의 랜덤한 숫자를 제공함.
ex) 0.4444444  0.8463513 등

그런데 위 기능은 0~9까지 숫자를 주는 것이 아니라 단순히 0~1사이 숫자를 주기때문에
하려고 하는 작업에 적합하지 않음.

그렇다면 어떻게 해야할까?

Math.random() 에 10을 곱하면 0에서 10사이의 숫자들을 얻을 수 있음!!!
ex) Math.random() * 10
--> 5.6040805    1.08498046

하지만 하고자하는 작업에서 소수점 밑의 숫자들까지 필요하지 않기 때문에
소수점 아래를 없애기 위해선 3가지 방법이 있음.
1. round : Math.round() --> 반올림
2. ceil : Math.ceil() --> 올림
3. floor : Math.floor() --> 버림

이 중 floor를 사용할 거임.

Math.floor(Math.random() * 10)

아래 코드대로 하면 콘솔창에 랜덤한 명언이 출력됨.

const quotes = [
        {quotes:"I never dreamed about sucess, i worked for it"},
        {quotes:"Do not try to be original just try to be good"},
        {quotes:"Do not be afraid to give up the good to go for the great"},
        {quotes:"Whatever you do, you have to keep moving forward"},
        {quotes:"The most certain way to succeed is always to try just one more time"},
        {quotes:"Some people dream of success, while other people get up every morning and make it happen"},
        {quotes:"The only thing worse than starting something and failing is not starting something"},
        {quotes:"You will face many defeats in life, but never let yourself be defeated"},
        {quotes:"The die is cast"},
        {quotes:"This too snail pass"}
]

const quote = document.querySelector("#quote span:first-child")

console.log(quotes[Math.floor(Math.random() * 10)])

하지만 * 10 이라는 숫자는 명언이 추가되거나 삭제되면 바뀌어야 할 숫자임.
매번 바꾸기엔 번거롭기 때문에

* quotes.length 로 변경

이제 화면에 출력해보면

const quote = document.querySelector("#quote span:first-child")
const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)]

quote.innerText = todaysQuote.quotes;

끗!

0개의 댓글