본문 바로가기

공부기록/[강의노트] 바닐라 JS로 크롬 앱 만들기

바닐라 JS로 크롬앱 만들기 #6.0~#6.2

#6.0 Quotes

 

인용문구를 만들어서 array를 만든다. 

Math 함수를 사용해서 랜덤 숫자를 가지고 온다. 

Math 함수를 랜덤하게 만들면 실수가 오는데, 그것에 10을 곱한 뒤 floor함수를 덧씌우면 

1~10까지 정수가 나오게 된다. 

Math.floor(Math.random() * 10)
console.log(quotes[Math.floor(Math.random() * 10)]);

quotes라는 array의 요소를 가져오려면 

console.log(함수명[인덱스명])

 

그런데 우리가 가지고 있는 인용어구 array의 길이를 기억해야하는 문제가 있다.

요소 수를 하나 더 추가하게 되면 또다시 숫자를 변경해야 하는 것이다. 

그러지 않으려면 숫자가 아닌 함수로 하면 된다.

 

숫자 10을 quotes.length라고 하면 된다. 

.length는 quotes array의 길이를 반환해 준다. 

 

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;

quote 에 할당된 위치에 todaysQuote의 quote 부분을 표시

author 에 할당된 위치에 todaysQuote의 author 부분을 표시

 

#6.1 Background

image파일을 HTML로 가져오는 것을 배워본다. 

 

const images = [
    "beautiful tree.jpg", "foward to mountain.jpg", "stars light.jpg"
];

먼저 image파일을 다운로드 받아서 img폴더에 넣고 array에 넣어 images 변수에 할당한다. 

chosenImage 변수에 랜덤으로 가져오는 함수를 할당한다. 

 

const chosenImage = images[Math.floor(Math.random() * images.length)];

 

그리고 HTML에 img라는 태그를 만들기로 한다. 

 

const bgImage = document.createElement("img");

bgImage.src = `img/${chosenImage}`;

document.body.appendChild(bgImage);

#6.2 Recap