

💚 다수의 명언을 랜덤 출력할 것
💚 Math.random()을 활용하여 인덱스를 랜덤으로 추출
🩵 명언과 작가의 정보를 받아올 span 태그 준비! 실질적인 텍스트는 스크립트로 받아올 것임.
<body>
<div id="quote">
<span></span>
<span></span>
</div>
</body>
🩵 quotes 라는 배열에 10개의 명언 객체를 저장
🩵 quotes 배열에서 랜덤한 명언을 선택 (랜덤한 배열 인덱스 만들기)
🔹 Math.random() : 0 이상 1 미만 범위에서 실수를 랜덤으로 반환
🔹 quotes.length를 곱하는 이유 : Math.random()이 반환하는 값에 quotes.length를 곱하면, 0 이상 quotes.length 미만의 랜덤한 실수가 반환
🔹 여기서 Math.floor() 를 써주면 내림 처리가 되어 0, 1, 2로 반환되어 변수에 저장된다.
🔹 최종적으로, 랜덤한 텍스트가 todaysQuote에 저장
💚 Math.random() : 0 이상 1 미만 사이의 랜덤 숫자를 반환 (소수점 단위)
🔸 Math.random() * 10 : 10 미만의 숫자를 반환하기 위해 곱하기 10
💚 Math.round(1.8) : 2로 반올림하여 반환
💚 Math.ceil(1.1) : 2로 올림하여 반환
💚 Math.floor(1.6) : 1로 내림하여 반환
<script>
const quotes = [
{
quote : "The only way to do great work is to love what you do.",
author : "Steve Jobs"
},
{
quote : "Do what you can, with what you have, where you are.",
author : "Theodore Roosevelt"
},
{
quote : "It always seems impossible until it’s done.",
author : "Nelson Mandela"
},
{
quote : "Happiness depends upon ourselves.",
author : "Aristotle"
},
{
quote : "Success is not final, failure is not fatal: it is the courage to continue that counts.",
author : "Winston Churchill"
},
{
quote : "If you want to go fast, go alone. If you want to go far, go together.",
author : "African Proverb"
},
{
quote : "In the middle of every difficulty lies opportunity.",
author : "Albert Einstein"
},
{
quote : "Life is really simple, but we insist on making it complicated.",
author : "Confucius"
},
{
quote : "Do what you feel in your heart to be right – for you’ll be criticized anyway.",
author : "Eleanor Roosevelt"
},
{
quote : "The best way to predict the future is to create it.",
author : "Peter Drucker"
}
]
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} -`;
</script>