인사하는것도 만들었고, 시계도 만들었고...이제 랜덤으로 나오는 명언과 배경이 남았다!!
이번 강의에서는 랜덤으로 명언이 출력되게 만들거다!
<div id="quote"> <span></span> <span></span> </div>
const quotes = [ { quote: "The way get started is to quit talking and begin doing.", author: "Walt Disney", },
이런 식으로 명언 10개를 array 형태로 만들어준다. 단순 text가 아니라, object형태로 만들어준다.
어떻게 array에 접근해야 할까? array[2] 이런식으로 총 10개라면 0~9까지 숫자가 들어가면 된다. 즉, 랜덤으로 숫자를 주면 된다.
우리는 math module을 사용할거다. JS에서 이미 load 돼서 공짜로 제공되고 있다. 흥미로운 함수들도 많이 가지고 있는데, 그 중 하나가 random( )이다.
random( ) : 0부터 1사이의 랜덤한 숫자를 제공한다.
Math.random( ) X 10 : 0부터 10 사이의 숫자들을 제공한다.
6.848571174894493
이런식(float)으로 출력되는데, 우리는 정수가 필요한거지. 소수는 필요없다.
round( ) : 반올림
ceil( ) : 올림
floor( ) : 버림
Math.floor(Math.random()*10)
위 코드는 0부터 9까지 랜덤하게 숫자를 출력해준다.
quotes[Math.floor(Math.random() * 10)]
우리는 명언 10개를 넣긴 했지만, 이게 수정될지 어떻게 알겠음? 그러니까 일일히 세는게 아니라 array의 길이를 알아내는게 좋다.
Array.length 활용
const quotes = [ { quote: "The way get started is to quit talking and begin doing.", author: "Walt Disney", }, ~~ 명언 총 10개 ] const quote = document.querySelector("#quote span:first-child"); const author = document.querySelector("#quote span:last-child"); const todaysQoute = quotes[Math.floor(Math.random() * quotes.length)]; quote.innerText = todaysQoute.quote; author.innerText = todaysQoute.author;
다음 강의는 랜덤 배경을 추가해보자!