바닐라 JS로 크롬 앱 만들기::복습 6.0~6.2
6.0
Math.random() : 랜덤 수를 반환하는 함수
ex. Math.random()*10을 하면 0에서 10 사이 랜덤 수 반환
-> Problem: 실수 형태로 반환하므로 이를 정수로 바꿔줄 함수가 필요하다.
실수-> 정수로 바꾸기 위한 함수가 크게 3가지가 있다.
-
round 함수
Math.round(1.1) -> 1
Math.round(1.9) -> 2
.4까지는 내리고, .5부터는 올린다. -
ceil함수
무조건 올린다.(천장)
Math.ceil(1.1) -> 2
Math.ceil(1.9) -> 2 -
floor함수
무조건 내린다.(바닥)
Math.floor(1.1) -> 1
Math.floor(1.9) -> 1
--> Math.floor(Math.random()*10)
0부터 9까지 숫자가 랜덤으로 나온다.
[array형태].length -> array 개수 반환
위 함수들을 이용하여 랜덤으로 격언을 화면에 띄어주는 기능을 구현한다.
const quotes=[{quote: "When you go through hardships and decide not to surrender, that is strength.",
author: "Arnold Schwarzenegger"
},{ quote: "There are better starters than me but I’m a strong finisher.",
author: "Usain Bolt"
},{ quote: "Tough times never last, but tough people do.",
author: "Robert H. Schuller"
},{ quote: "I’ve failed over and over and over again in my life and that is why I succeed.",
author: "Michael Jordan"
},{ quote: "If you don’t get out of the box you’ve been raised in, you won’t understand how much bigger the world is.",
author: "Angelina Jolie"
},
{ quote: "The way to get started is to quit talking and begin doing.",
author: "Walt Disney",
}];
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;
6.1
6.0와 거의 유사한데, 랜덤으로 이미지를 띄우는 기능을 구현한다. 6.0와 차이점은 js에서 html으로 태그를 생성해내는 것이다. 코드는 다음과 같다.
const images = [
"0.jpg", "1.jpg","2.jpg"
];
const chosenImage=images[Math.floor(Math.random()*images.length)];
const bgImage= document.createElement("img");
bgImage.src=`img/${chosenImage}`;
document.body.appendChild(bgImage);
이때, 이미지 파일명과 일치해야함을 주의하자.
6.3 총복습
Author And Source
이 문제에 관하여(바닐라 JS로 크롬 앱 만들기::복습 6.0~6.2), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@changhee1016/바닐라-JS로-크롬-앱-만들기복습-6.06.2저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)