https://developer.mozilla.org/ko/docs/Learn/JavaScript/First_steps/Silly_story_generator
Silly story generator - Web 개발 학습하기 | MDN
이 모듈에서 배운 지식들을 바탕으로 랜덤하게 꾸며진 이야기(silly stories)가 만들어지는 재미있는 앱을 만들어 볼거에요. 즐겨봅시다!
developer.mozilla.org
문제 및 풀이
사이트 문제가 다 한국어로 되어 있어서 읽는 데에 크게 불편함은 없을 거 같아요. 그래도 간략하게 설명할게요.
이 문제는 input에 이름을 입력하면 그 이름을 입력받아 무작위 이야기를 만들어 내도록 구현해야 합니다.
index.html, raw-text.txt, main.js 파일을 만들며 다 같은 디렉토리 그러니까 폴더에 있습니다.
사이트의 설명을 차근차근 따라가면 문제 없이 구현할 수 있는데 헷갈리는 부분이 있어서 그 부분만 기록할게요.
insertX, insertY, insertZ 변수는 아래의 코드에서 보실 수 있듯이 배열로 저장해야 해요. 그치만 raw-text.txt에서는 문자열로 되어 있기 때문에 바꿔줘야 해요. 그래야 나머지의 코드에서 함수가 잘 동작해요.
storyText 변수 :insertX: 부분은 두 군데나 바꿔야 해요. 그래서 문자열replace 메서드를 쓰기 보다는 replaceAll 함수를 사용해서 바꿔주는 게 훨씬 편해요.
문자열 합치는 경우에는 리터럴 템플릿(``)을 사용해서 변수에 저장하였더니 좀 더 편하게 바꿀 수 있었어요.
이해 안 가시거나 질문 있으시면 댓글 달아주세요!
코드
html문서는 </body> 바로 앞에 <script src="main.js></script> 이것만 추가했어요. 넘어갈게요!
main.js
const customName = document.getElementById("customname");
const randomize = document.querySelector(".randomize");
const story = document.querySelector(".story");
function randomValueFromArray(array) {
const random = Math.floor(Math.random() * array.length);
return array[random];
}
storyText =
"It was 94 fahrenheit outside, so :insertx: went for a walk. When they got to :inserty:, they stared in horror for a few moments, then :insertz:. Bob saw the whole thing, but was not surprised — :insertx: weighs 300 pounds, and it was a hot day.";
insertX = ["Willy the Goblin", "Big Daddy", "Father Christmas"];
insertY = ["the soup kitchen", "Disneyland", "the White House"];
insertZ = [
"spontaneously combusted",
"melted into a puddle on the sidewalk",
"turned into a slug and crawled away",
];
randomize.addEventListener("click", result);
function result() {
let newStory = storyText;
let xItem = randomValueFromArray(insertX);
let yItem = randomValueFromArray(insertY);
let zItem = randomValueFromArray(insertZ);
newStory = newStory.replaceAll(":insertx:", xItem);
newStory = newStory.replace(":inserty:", yItem);
newStory = newStory.replace(":insertz:", zItem);
if (customName.value !== "") {
const name = customName.value;
newStory = newStory.replace("Bob", name);
}
if (document.getElementById("uk").checked) {
const weight = `${Math.round(300 * 0.071429)}stone`;
const temperature = `${Math.round(((94 - 32) * 5) / 9)} centigrade`;
newStory = newStory.replace("94 fahrenheit", temperature);
newStory = newStory.replace("300 pounds", weight);
}
story.textContent = newStory;
story.style.visibility = "visible";
}
결과
이름을 넣지 않고 단위가 UK가 기준인 경우의 결과
이름을 Kim라고 하고 단위가 US 기준인 경우의 결과
사이트 번역이 잘 안되어 있어서 살짝씩 의역해야할 때도 많아요.
오류 있으면 댓글 남겨주세요. 감사합니다!
'Computer > HTML, CSS, Javascript' 카테고리의 다른 글
[Javascript] 과제: 조건 (3) | 2024.10.27 |
---|---|
[Javascript] 과제: 배열 (1) | 2024.10.25 |
[Javascript] 과제: 기본적인 연산 (3) | 2024.10.25 |
[Javascript] 과제: 변수 (1) | 2024.10.24 |
[CSS] 과제: 레이아웃 (2) | 2024.10.24 |