JS

js 기초정리(5) math 객체

양양00 2022. 10. 11. 20:34

Math 객체 사용해보기

//   명언들을 배열시켜서 랜덤으로 나오게 하기

 

quote.js 파일을 따로 만들어줌 // 굳이 안만들어도 되긴한다.. (보기 편하게)

 

html에 <div id = "quote" >   <span>태그 두개를 미리 넣어줌

 

10가지 명언들을 array로 넣어놓기  ( string으로 넣으면 math 객체 사용못함) 

const quotes = [
    {
    quote: 'I never dreamed about success, I worked for it',
    author: 'Estee Lauder'
    },
    {
    quote: 'Do not try to be original, just try to be good.',
    author: 'Paul Rand'
    },
    {
    quote: 'Do not be afraid to give up the good to go for the great',
    author: 'John D. Rockefeller'
    },
    {
    quote: 'If you cannot fly then run. If you cannot run, then walk. And if you cannot walk, then crawl, but whatever you do, you have to keep moving forward.',
    author: 'Martin Luther King Jr.'
    },
    {
    quote: 'Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.',
    author: 'Thomas Edison'
    },
    {
    quote: 'The fastest way to change yourself is to hang out with people who are already the way you want to be',
    author: 'REid Hoffman'
    },
    {
    quote: 'Money is like gasoline during a road trip. You do not want to run out of gas on your trip, but you are not doing a tour of gas stations',
    author: 'Tim O Reilly'
    },
    {
    quote: 'Some people dream of success, while other people get up every morning and make it happen',
    author: 'Wayne Huizenga'
    },
    {
    quote: 'The only thing worse than starting something and falling.. is not starting something',
    author: 'SEth Godin'
    },
    {
    quote: 'If you really want to do something, you will find a way. If you do not, you will find an excuse.',
    author: 'Jim Rohn'
    },
    ];

 

// math.random() : 0-1 사이 랜덤 제공    //math 모듈은 js에 이미 로드 돼있음
// math.round() : 소수점을 내림해서 정수로 나타냄
// math.ceil() : 소수점을 올림해서 올림
// math.floor(): 소수점을 무조건 반내림해서 정수로 만듬
const quote = document.querySelector("#quote span:first-child");
const author = document.querySelector("#quote span:last-child"); 
// ------> querySelector로 id="quote"에 span 자식선택자로 불러온다."


const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)]; 
// ------> quote의 length만큼 random을 돌린후 -> 소수점을 내림 >> 정수(인덱스 번호)가 나옴

quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;    // quote와 ,author에 todaysQuote를 innerText해줌

 

 

 

 

// 배경img random으로 나오게 하기

 

img 파일에 3개이상 이미지를 저장해놓아야함

const images = [ "0.jfif","1.jfif","2.jfif"]     // 저장된 이미지 파일 이름을 똑같이 넣어야함
// -----> array로 인덱스 번호 지정

const chosenImage = images[Math.floor(Math.random() * images.length)];  
// 랜덤으로 이미지를 돌림 (위(qoute)식과 같음)

 

+ js파일에서 html img파일 추가하기

creatEelement("") : html에 요소 추가 

const bgImage = document.createElement("img")  
// createElement("")를 사용해 html 내에 img 태그 생성

// console.log(bgImage)       // 콘솔창에 뜨지만, html element는 없음

bgImage.src=`img/${chosenImage}`;      //html파일에서 <img src=""/>를 넣은것과 마찬가지
//----> js에서 랜덤string(img아님)으로 html element를 만듬


document.body.appendChild(bgImage);      
//---->img를 body내부에 추가

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