본문 바로가기
MINI PROJECT/JavaScript

명언제조기

by jono 2021. 8. 22.

PROJECT 05 >>>

명언제조기 만들기

프로그래머 명언

 

 # 새로 배운 점 

 

1. 난수를 인덱스로 지정하여 배열데이터에 접근하는 방법

let index = Math.floor( Math.random( ) * arrayName.length );

 

2. addEventListener("이벤트", 함수);

 해당 함수는 밑에 서술한다.

 


 # 코드 

- css속성은 생략함.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">  
  <title>Generate Quote</title>
</head>

<body>
<fieldset>
  <h3 id="quote" >"The only way to learn a new programming language is by writing programs in it."</h3>
  <h4>by <span id="author">"Dennis Ritchie"</span></h4>
</fieldset>
<br>
<div>
  <input type="button" value="Generate Quote!" id="btn">
</div>


<script>
const quotes = [
  {
    quote:
    "Testing leads to failure, and failure leads to understanding.",
    author: "Burt Rutan"
  },
  {
    quote: 
    "The most damaging phrase in the language is..it's always been done this way",
    author: "Grace Hopper"
  },
  {
    quote:
    "Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program.",
    author: "Linus Torvalds"
  },
  {
    quote:
    "The most important single aspect of software development is to be clear about what you are trying to build.",
    author: "Bjarne Stroustrup"
  },
  {
    quote:
    "Because the ones who are crazy enough to think that they can change the world, are the ones who do.",
    author:"Steve Jobs"
  },
  {
    quote:
    "Any fool can write code that a computer can understand. Good Progranner write code that humans can understand.",
    author:"Martin Fowler"
  }
];

    // 1) html의 각 요소를 가져와 변수에 저장.
    const $btn = document.querySelector("#btn");
    const $quote = document.querySelector("#quote");
    const $author = document.querySelector("#author");

    // 2) 버튼을 클릭했을 때, generator 함수가 실행되도록 설정
    $btn.addEventListener("click", generator); 
     
    // 3) generator함수생성
    function generator(){
    // 함수의 기능-1)  인용구가 저장되어있는 list배열의 크기를 최댓값으로 갖는 난수를 생성하여 인덱스로 지정함.
     let index = Math.floor( Math.random() * quotes.length);
    
    // 함수의 기능-2) 생성된 인덱스를 통해 list배열의 데이터에 접근하여 quote와 author를 html화면에 띄운다.
      $quote.textContent = quotes[index].quote;
      $author.textContent = quotes[index].author;      
  
    };
      
</script>

</body>
</html>

 # 프로젝트 아이디어 출처 

 

 

Random Quotes JavaScript Project - JSBeginners

This Random Quotes project is fairly simple. It calls for you to access the properties on an object that's embedded inside of an Array. When the "Generate Quote" button is pressed, it triggers a change in quote and the author who said it.

jsbeginners.com

 

댓글