#6.0 랜덤으로 명언 보여주기(Quotes/바닐라 JS로 크롬 앱 만들기)

hmLee·2021년 10월 20일
0

화면 로드 시 명언을 보여주려고 한다.

  <div id="quote">
    <span></span>
    <span></span>
  </div>

It's better to have loved and lost, than never to have loved at all
Alfred, Lord Tennyson

처럼 명언, 작가 순으로 보여주기 위해 html에는 span을 2개 넣고 이를 div.quote로 묶었다.

명언은 10개를 준비했고 이를 배열로 js파일에 작성했다.

const quotes = [
  {
    quote:
      "It's better to have loved and lost, than never to have loved at all",
    author: "Alfred, Lord Tennyson",
  },
  {
    quote:
      "There is always some madness in love. But there is also always some reason in madness",
    author: "Friedrich Nietzsche",
  },
  
//...생략

];

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)];

그리고 명언과 작가를 보여줄 span을 quote와 author로 선언했다.

명언들은 랜덤으로 화면에 보여줄 것이기 때문에
명언 개수까지의 숫자를 랜덤으로 뽑아내야했고
우선 0~1사이의 수를 무작위로 보여주는 Math.random() 함수를 사용했다.

그리고 명언이 나중에 추가될 수도 있기 때문에 10을 곱하기 보다는
quotes.length를 곱했다.

Math.random() * quotes.length

소수점 자리는 필요가 없기 때문에
Math.floor함수를 사용해서 내림을 하기로 했다.

Math.round();//반올림
Math.ceil();//올림
Math.ceil();//내림

Math.floor(Math.random() * quotes.length)

이로써 0~9사이의 숫자를 랜덤으로 호출할 수 있게 했고
quotes에서 그 숫자에 해당하는 배열데이터를 호출하기 위해 아래와 같이 작성했다.

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

그리고 마지막으로 뽑아낸 데이터를 html안에 넣어주었다.

quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;
profile
정말 개발자가 될 수 있을까?

0개의 댓글