JavaScript로 크롬 앱 만들기 #13

Heeseung Ha·2022년 1월 21일
0

노마드 코더 - 바닐라 JS로 크롬 앱 만들기 #13

💻 실습 코드

  • HTML → 저번에 실습했던 코드에 quotes.js, background.js를 추가해줌
// quotes.js
const quotes = [
  {
    quote:
      "Nothing in life is to be feared, it is only to be understood. Now is the time to understand more, so that we may fear less.",
    author: "Marie Curie",
  },
  ...(이런식으로 배열요소 10개 생성)
];

const quote = document.querySelector("#quotes span:first-child");
const author = document.querySelector("#quotes span:last-child");

const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];

quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;
// background.js
const images = ["river.jpg", "cliff.jpg", "coast.jpg"];

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

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

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

document.body.appendChild(bgImage);

✔ Math.Random( )

  • 0~1 사이의 난수를 생성하는 함수
const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];
  • quotes 배열에서 랜덤하게 명언을 추출하기 위해 Math.random()을 사용했다.

  • 이때 random을 통해 생성한 수가 0~1 사이의 수이기 때문에 소수점을 제거해주기 위해 floor를 사용했다.

    Math.ceil() : 소수점을 무조건 올려서 정수로 반환
    Math.round() : 소수점을 반올림해서 정수로 반환
    Math.floor() : 소수점을 무조건 내려서 정수로 반환

  • 지금 예제야 무작위로 추출할 내용이 10개 뿐이지만, 그 이상일 때는 일일이 숫자를 세기가 힘드므로 array.length()를 사용해서 배열 요소의 크기만큼 돌리도록 지정했다.

✔ createElement( )

  • JavaScript에서 HTML에 요소를 추가하는 방법
const bgImage = document.createElement("img");
bgImage.src = `img/${chosenImage}`;
document.body.appendChild(bgImage);
  • 내 로컬 저장소에 있는 사진을 페이지에 띄우기 위해 createElement()를 사용해서 img태그인 bgImage라는 변수를 추가했다.
  • bgImage의 소스를 지정해준다. 랜덤한 이미지를 보여줄 것이므로 chosenImage가 소스 부분에 쓰인다.
  • appendChild를 통해 body부분에 bgImage라는 img태그를 추가(append) 해준다.
profile
FE 개발 공부중...💫

0개의 댓글