천천히 알아보는 코딩공부

javascript 랜덤 본문

JavaScript/예제

javascript 랜덤

고기고기물고기 2022. 3. 31. 00:40

javascript 랜덤으로 배열에있는 문자열 출력

const quotes = [
    {
        quote : "a",
        author : "daeseok1",
    
    },
    {
        quote : "b",
        author : "daeseok2",
    }
]

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; //quote 위치에 랜덤 quote 출력
author.innerText = todaysQuote.author; //author 위치에 랜덤 author 출력
  • a daeseok1, b daeseok2 중 결과값이 랜덤으로 출력된다.
  •  

javascript 랜덤으로 배열에있는 이미지 출력

const images = ["1.jpg", "2.jpg", "3.jpg"]

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

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

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

document.body.appendChild(bgImage);
Comments