새소식

Frontend/JavaScript

[JavaScript] 노마드코더 강의 정리 - Quotes & Background

  • -

 

📒 Quotes

const quotes = [
  {
    quote: "Be yourself; everyone else is already taken.",
    author: "Oscar Wilde",
  },
  {
    quote:
      "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.",
    author: "Albert Einstein",
  },
  {
    quote: "A room without books is like a body without a soul.",
    author: "Marcus Tullius Cicero",
  },
  , ...
];

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;

 

  • array 안에 object 여러 개 나열하는 형태의 quotes 변수
  • [ {}, {}, {}, {}, {}, {}, ] --> 콤마 꼭 작성하기!
  • array.length : 배열의 길이 알려주는 property
  • Math.floor(Math.random())
    : Math.random() 함수는 0 이상 10 미만의 랜덤 소수를 반환하므로 Math.floor 함수를 이용해 소수를 정수로 변환
  • Math.round 반올림
  • Math.ceil 올림
  • Math.floor 내림

 

📒 Background

const images = [
  "img0.jpg",
  "img1.jpg",
  "img2.jpg",
  "img3.jpg",
  "img4.jpg",
  "img5.jpg",
  "img6.jpg",
  "img7.jpg",
  "img8.jpg",
  "img9.jpg",
];

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

const bgImage = document.createElement("img");
// createElement property의 태그
// 태그와 폴더명이 같아야 해서 img로 설정

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

document.body.appendChild(bgImage);
// appendChild() -> 맨 뒤에 삽입, 오래된 브라우저에서도 지원
// prepend() -> 맨 위에 삽입

 

  • DOM을 이용하면 HTML의 요소를 JS에 불러올 수도 있지만 createElement를 이용해
    JS에서 HTML에 새로운 요소를 생성할 수도 있다. Very Awesome!!!! 왜 DOM 쓰는지 점점 이해가 된다.

 


 

 

 

참고 자료

 

바닐라 JS로 크롬 앱 만들기 – 노마드 코더 Nomad Coders

Javascript For Beginners

nomadcoders.co

 

Math.random() - JavaScript | MDN

Math.random() 함수는 0 이상 1 미만의 구간에서 근사적으로 균일한(approximately uniform) 부동소숫점 의사난수를 반환하며, 이 값은 사용자가 원하는 범위로 변형할 수 있다. 난수 생성 알고리즘에 사용

developer.mozilla.org

 

 

 

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.