JavaScript #17

haechi·2021년 8월 4일
0

Web

목록 보기
18/69

210804
JavaScript #17


10개의 명언을 랜덤으로 나오도록 해보자

-quotes.js
10개의 quote,author 를 만들어준다.

  • randomness
    무작위성

-Math module
JS에서 기본제공
Math.random()
0부터 1사이의 랜덤한 숫자를 반환한다.

Math.random() * 10 을 한다면 0~10 의 숫자를 받을 수 있고
현재 숫자의 형태를 보면 Integer가 아닌 float 형이 나온다.

Interger 형으로 받기 위해서는 어떻게 하는가?
3가지의 function이 있다.

  1. round()
    반올림
  2. ceil()
    올림
  3. floor()
    버림

현재 원하는 값은 1~10 사이의 랜덤한 정수이다.
Math.floor(Math.random()*10) 으로 사용할 수 있다.

-quotes.js

const quotes = [{quote: " ...", authoer: "..."},{....},]

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

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

현재 코드는 10개로 정해뒀기 때문에 10이라고 썼지만 더 늘어나거나 변경을 위해서 length를 사용한다.

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

이제 이 명언을 화면에 출력되도록 해보자

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

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

quote.innerText = todaysQuote.quote
author.innerText = todaysQuote.author

참고
https://nomadcoders.co/javascript-for-beginners/lobby

명언 출처
카카오톡 이모티콘 '명언인줄'

profile
공부중인 것들 기록

0개의 댓글