📌Language/JavaScript

자바스크립트로 크롬 앱 만들기 - 노마드 코더 클론코딩 #10 quotes 함수, 이미지를 html body에 추가하는 방법

hellohailie 2022. 4. 11. 22:32

<quotes 함수>

 

* quotes 함수는 배열이다!

* 쉼표를 조심하자!

 


Math 객체 기능 (Math Module)

 

 

 

Math module은 JS에서 이미 load돼서 공짜로 제공되고 있다. 
ex) Math.PI

 

 

 


<Math.random()>
Math.random()은 0부터 1 사이의 랜덤한 숫자를 제공한다. 


응용도 가능!! Math.random() * 10 

 

0.0 <= Math.random() < 1.0

 

3미만의 숫자를 뽑고싶다!

0.0 * 3 <= Math.random() * 3 < 1.0 * 3

 

=> Math.random() 는 0.0 부터 2.9999999까지만 가능

 

 7미만의 숫자를 뽑고싶다!

0.0 * 7 <= Math.random() * 7 < 1.0 * 7

 

=> Math.random() 는 0.0 부터 6.999999까지만 가능

 

⭐️⭐️⭐️즉, Math.random() * 원하는 숫자⭐️⭐️⭐️

 

 


<Math.round()>

반올림 해서 정수만 보여준다. 

 

<Math.ceil()>

올림 해서 정수만 보여준다. 숫자를 천장(ceil)까지 높여주는거다. 

 

Math.ceil(1.01) => 2

 

<Math.floor()>

내림 해서 정수만 보여준다. 숫자를 바닥(floor)까지 내려준다. 

 

 


[1,2,3,4,5] 이렇게 생긴 array가 있을 때, Array.length를 사용하면 Array의 길이를 반환해준다. 

 

 

 


 

<JS에서 html 요소 생성하기>

createElement("") 를 사용하자.
예를 들어,
document.createElement("img")일 경우 html 내에 img 태그를 생성

 

const images = ["0.JPG","1.JPG","2.JPG"]

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

console.log(chosenImages);

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

image.src = `img/${chosenImages}`;
console.log(image);

 

 

 

 

 


 

<이미지를 html body에 추가하기>

 

**appendChild() => body에 추가하는 역할

document.body.appendChild(image);

 

 

<참고>

appendChild()
// 함수 안의 경로에 정의한 값을 가장 뒤에서 기입함
prependChild()
// 반대로 앞에서 기입

 

 

 

Element 창에 이미지가 심어져 있다.