Math 메서드로 랜덤하게 배열의 요소 가져오기

Wonju·2021년 12월 9일
0

Math 메서드 수없이 많음

그 중 하나 많이 쓰는 것

Math.random()

= 0에서 1 사이의 수를 가져온다.

0 에서 10 사이의 숫자가 필요하다면?

Math.random() * 10 하면 된다.

하지만 소수점 자리도 필요가 없으니까

소수점 자리는 버려주는 몇가지 방법이 있다.

1. Math.round()

반올림해주는 메서드
1.1 ~ 1.4 = 1 로 반환
1.5 ~ 1.9 = 2 로 반환

2. Math.ceil()

올림해주는 메서드
1.0 만 1로 반환
1.01 이어도 2로 반환

3.Math.floor()

내림해주는 메서드. 소수점뒷자리는 그냥 버리는 것.

여기선 Math.floor() 메서드를 사용해준다.

Math.floor(Math.random() * 10)


응용해서 03 05 01 이렇게 뜨게 하고 싶다면

이전에 배운 padStart를 사용해서

String(Math.floor(Math.random() * 10)).padStart(2,"0");
해주면
'03' '02' '09' 이렇게 뜬다.


const quotes = [
  	// 배열 안에 10개의 객체들이 있는 형태임
  {
    quote: "Be yourself; everyone else is already taken.",
    author: "Oscar Wilde",
  },
  { quote: "So many books, so little time.", author: "Frank Zappa" },
  {
    quote: "Without music, life would be a mistake.",
    author: "Friedrich Nietzsche",
  },
  {
    quote: "If you tell the truth, you don't have to remember anything.",
    author: "Mark Twain",
  },
  {
    quote:
      "In three words I can sum up everything I've learned about life: it goes on.",
    author: "Robert Frost",
  },
  {
    quote: "A room without books is like a body without a soul.",
    author: "Marcus Tullius Cicero",
  },
  {
    quote: "The way to get started is to quit talking and begin doing.",
    author: "Walt Disney",
  },
  {
    quote:
      "If you set your goals ridiculously high and it's a failure, you will fail above everyone else's success.",
    author: "James Cameron",
  },
  {
    quote:
      "It is during our darkest moments that we must focus to see the light.",
    author: "Aristotle",
  },
  {
    quote: "Life is ours to be spent, not to be saved.",
    author: "D. H. Lawrence",
  },
];

const quote = document.querySelector("#quote span:first-child");
const author = document.querySelector("#quote span:last-child");

// 0부터9까지의 명언을 가져오는 function

console.log(quotes[Math.floor(Math.random() * 10)]);
// 랜덤하게 quotes 배열의 요소들이 뜨는 것을 알 수 있다.

명언이 10개 였기에 Math.random() * 10 을 했는데
만약 명언이 계속 늘어난다면? 일일이 그때마다 숫자를 넣어주는것은 ㄴㄴ

length 라는 기능 사용하기.

Array.length 를 해주면 배열의 길이를 반환해준다.

quotes.length 하면 10 나오는 것.

console.log(quotes[Math.floor(Math.random() * quotes.length)]);

뒤에 10 대신 quotes.length 로 바꿔줘도 아주 잘 작동한다.

const quotes = [
...
];

const quote = document.querySelector("#quote span:first-child");
const author = document.querySelector("#quote span:last-child");

// 0부터9까지의 명언을 랜덤하게 가져오는 코드
const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];

quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;
// 위에서 선언한 quote와 author(#quote라는 div의 첫번째/마지막
// span의 innerText(id와 class선언안해도 이렇게 지정가능)를
// quotes라는 배열의 랜덤한 요소 속의 quote와 author를 각각 불러주기
// 길게쓰니까 더 헷갈리는거같네
profile
안녕하세여

0개의 댓글