| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 |
Tags
- 백준
- 백준10815
- TypeScript
- zustand
- styled-components
- 정처기실기
- JS
- 백준5086
- Vue
- 백준2501
- 바닐라js
- JavaScript
- 백준10798
- reactrouter
- 10815
- 정처기필기
- 투두리스트
- Vue3
- NextJs
- 코딩테스트
- 파이썬
- 자바스크립트
- 코테
- 정보처리기사
- 이벤트버블링
- react
- 리액트
- 타입스크립트
- 코딩테스크
- 정처기
Archives
- Today
- Total
윤시의 블로그
To-Do List 만들면서 정리한 JavaScript - 랜덤 출력 본문

투두리스트를 만들며 새로고침 할 때마다
화면에 명언을 랜덤으로 출력하는 코드 정리
// 1. 명언(quote)과 저자(author)를 저장한 배열을 생성
// 배열 내 각 항목은 quote와 author 속성을 가진 객체
const quotes = [
{
quote: "The way to get started is to quit talking and begin doing.",
author: "Walt Disney",
},
{
quote: "Life is what happens when you're busy making other plans.",
author: "John Lennon",
},
{
quote: "The world is a book and those who do not travel read only one page.",
author: "Saint Augustine",
},
{
quote: "Life is either a daring adventure or nothing at all.",
author: "Helen Keller",
},
{
quote: "To Travel is to Live",
author: "Hans Christian Andersen",
},
{
quote: "Only a life lived for others is a life worthwhile.",
author: "Albert Einstein",
},
{
quote: "You only live once, but if you do it right, once is enough.",
author: "Mae West",
},
{
quote: "Never go on trips with anyone you do not love.",
author: "Hemingway",
},
{
quote: "We wander for distraction, but we travel for fulfillment.",
author: "Hilaire Belloc",
},
{
quote: "Travel expands the mind and fills the gap.",
author: "Sheda Savage",
},
];
// 2. HTML의 특정 요소를 선택하여 변수에 저장
// #quote 요소 내 첫 번째 <span> 요소와 마지막 <span> 요소를 각각 선택하여 quote와 author 변수에 할당
const quote = document.querySelector("#quote span:first-child");
const author = document.querySelector("#quote span:last-child");
// 3. 랜덤 명언 선택
// Math.random()을 사용해 0과 배열의 길이 사이의 임의의 숫자를 생성하고,
// Math.floor()를 통해 정수로 변환하여 quotes 배열의 인덱스로 사용
const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];
// 4. HTML 요소의 innerText 속성을 사용하여 화면에 표시할 내용을 설정
quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;
코드 주요 개념
1. 객체와 배열
- 명언과 저자를 효율적으로 관리하기 위해 각각의 명언을 quote와 author 속성을 가지는 객체로 정의하고, 이를 배열(quotes)에 저장한다. 객체와 배열을 함께 사용하면, 특정 명언에 접근할 때 쉽게 원하는 속성에 접근할 수 있다.
- quotes 배열은 여러 개의 명언 객체를 포함하고 있으며, 각 객체는 { quote: "...", author: "..." }의 형태로 구성되어 있다.
예를 들어, quotes[0]은 {"quote": "The way to get started is to quit talking and begin doing.", "author": "Walt Disney"}
이를 통해 명언 데이터가 깔끔하게 관리되며, 명언의 개수를 추가하거나 수정할 때 코드 변경이 용이하다.
2. 랜덤 요소 선택
- Math.random()과 Math.floor()를 사용하여 배열의 길이(quotes.length) 내에서 임의의 정수를 생성하여 배열의 요소를 랜덤하게 선택한다.
- Math.random()은 0부터 1 사이의 실수를 반환하므로, 이를 quotes.length와 곱해줌으로써 0 이상, quotes.length - 1 이하의 실수가 만들어진다. 그 후, Math.floor()를 사용해 소수점을 버리고 정수로 변환하여 배열의 인덱스 값으로 사용한다.
이런 방식으로 매번 다른 명언이 화면에 랜덤하게 표시된다.
3. DOM 요소 선택
- HTML 문서 내의 특정 요소를 조작하려면 JavaScript에서 해당 요소를 선택해야 한다. document.querySelector를 사용하여 #quote 아이디를 가진 요소 내의 첫 번째 span과 마지막 span 요소를 각각 quote와 author 변수에 할당한다.
- "#quote span:first-child"는 #quote 요소의 자식 span 중 첫 번째 요소를 의미하고,
- "#quote span:last-child"는 마지막 span 요소를 의미함
const quote = document.querySelector("#quote span:first-child"); const author = document.querySelector("#quote span:last-child");
이를 통해 명언 텍스트와 저자 이름을 각각 다른 HTML 요소에 표시한다.
4. 코드 확장성
- 만약 명언을 추가하고 싶을 경우, quotes 배열에 새로운 객체를 추가하기만 하면 된다.
- 예를 들어:
quotes.push({ quote: "Your new quote here.", author: "Author Name", });
- 추가된 명언도 코드 수정 없이 랜덤하게 출력된다.
'JavaScript' 카테고리의 다른 글
| [JavaScript] 제어구문 (1 - 조건문) (1) | 2024.12.01 |
|---|---|
| [JavaScript] (함수, 함수 표현식, 화살표 함수 기본) (1) | 2024.11.29 |
| To-Do List 만들면서 정리한 JavaScript - Timer (1) | 2024.10.08 |
| To-Do List 만들면서 정리한 JavaScript - login (1) | 2024.10.06 |
| [JavaScript] 기본 문법 정리 #2 (1) | 2024.08.10 |