언어&프레임워크/JavaScript

Quotes 웹페이지에 랜덤으로 보여주기(random, floor in JavaScript)

밍풀 2022. 12. 12. 00:30

1. 명언이 들어간 배열이 포함된 quotes.js 파일을 따로 만들어줌

2. html에 js 연결, 명언이 들어갈 자리도 마련해줌

 

3. quotes 배열에서 랜덤하게 불러오게 만들기=random함수이용

Math.random() 함수 = 0~1사이의 랜덤한 숫자 제공

 

0~10사이 랜덤한 수 얻고 싶을 때 10 곱하면 됨(인용문구가 10개 라서)

 

그런데 배열에서 사용하기 위해선 소숫점 떼버리고 정수를 얻고 싶으니 내림 함수 사용

floor= 내림, ceil=올림, round=반올림

+) 그런데 만약에 인용구가 추가되어 15개가 됐을때, 0~14 까지의 랜덤한 수를 추출하고 싶다면?

위의 10 자리에 15를(인용구 갯수) 를 넣어주면 됨

0<Math.random()<1 이고 

따라서 모든항에 15 곱하면 0< Math.random()* 15< 15   가 성립하므로

Math.random()*15 하면 0보다크고 15보다 작은 수가 나오게 되고, 이를 내림하면 0~14 까지의 정수가 무작위로 나오게됨 끄읏~

 

이를 코드에 적용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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'
    },
    ];//인용구들을 모아놓은 배열
 
 
    const quote = document.querySelector("#quote span:first-child");
    //id가 quote인 것, 그안에서 span의 첫번째
    const author = document.querySelector("#quote span:last-child");
    const todaysQuotes = quotes[Math.floor(Math.random()*quotes.length)];
    //quotes 배열에서 랜덤하게 하나 가져와 변수에 저장
    quote.innerText = todaysQuotes.quote;//가져온 배열에서 quote부분
    author.innerText = todaysQuotes.author;
 
cs

 

랜덤하게 명언이 나오게되었음