본문 바로가기

일/javascript

js04_function

 /*
     함수(function)란?

     1. 함수는 기본적으로 호출된 곳으로 처리결과를 전달해주는 기능을 한다.
     2. 함수의 호출은 '함수명()'의 형태로 호출한다.
     3. 함수의 소괄호 안에는 함수로 임의의 값을 전달하는 매개변수(매개값, 인자, 파라미터...)가
        있을 수도 있고 없을 수도 있다.
     4. 사용자함수의 정의방법
        1) 익명함수 : 이름이 없는 함수 : function() {...}
        2) 선언함수 : 이름이 있는 함수 : function 함수명(매개변수...) {...}
     
      내장함수와 사용자(정의)함수

      1. 내장함수 : JavaScript에서 기본적으로 제공해 주는 함수를 내장함수라 한다.
          예) alter, prompt, confirm...
      2. 사용자 정의함수
        1) 익명함수
        2) 선언함수

    */

    //익명함수
    //  let fn01 = function (){
    //   return '반환된 값';
    //  }
    //  let result = fn01();
    //  console.log(typeof fn01, ',',result);
    //  console.log(`${fn01()}`);



     // 2) 재사용하기 위한 함수 : 재사용
    //     let fn02 = function add(a, b){ return a + b;}
    //     result = fn02(10, 20);
    //     console.log(`10 + 20 = ${result}`);
    //     console.log(`100 + 300 = ${fn02(100, 300)}`);

    // // 2. 선언함수
    // function fn03(a, b){return a * b;}
    // result = fn03(10, 20);
    // console.log(`10 * 20 = ${result}`);
    // console.log(`100 * 300 = ${fn03(100, 300)}`);

    /* 실습1. 계산기 함수를 작성해 보세요
    매개변수가 3개인 calculator(연산자, 값1, 값2)
     연산자 : + - * / % d
     각 연산자에 따라 값1과 값2의 연산결과를 출력
     document.write(`값1 + 값2 = 결과값`)
     document.write(`값1 - 값2 = 결과값`)
     document.write(`값1 * 값2 = 결과값`)
     document.write(`값1 / 값2 = 결과값`)
     document.write(`값1 % 값2 = 결과값`)


    */
</script>
  <script>
    function fn01(a, b){return a + b;}
    result = fn01(10, 20);
    console.log(`${result}`);
   

    function fn02(a, b){return a - b;}
    result2 = fn02(10, 20);
    console.log(`${result2}`);
   

    function fn03(a, b){return a * b;}
    result3 = fn03(10, 20);
    console.log(`${result3}`);
   

    function fn04(a, b){return a / b;}
    result4 = fn04(10, 20);
    console.log(`${result4}`);
   

    function fn05(a, b){return a % b;}
    result5 = fn05(10, 20);
    console.log(`${result5}`);
     



    document.write(`10 + 20 = ${fn01(10, 20)} <br>`);
    document.write(`10 - 20 = ${fn02(10, 20)}<br>`);
    document.write(`10 * 20 = ${fn03(10, 20)}<br>`);
    document.write(`10 / 20 = ${fn04(10, 20)}<br>`);
    document.write(`10 % 20 = ${fn05(10, 20)}<br>`);
  </script>
 

계산기.html !!!

 <script>
   
    function add(){
      let fnum = parseInt(document.getElementById('fnum').value);
      let snum = parseInt(document.getElementById('snum').value);
      let result = fnum + snum;
      document.getElementById('result').innerHTML = result;

    }
    function sub(){
      let fnum = parseInt(document.getElementById('fnum').value);
      let snum = parseInt(document.getElementById('snum').value);
      let result = fnum - snum;
      document.getElementById('result').innerHTML = result;
    }
   function mul(){
      let fnum = parseInt(document.getElementById('fnum').value);
      let snum = parseInt(document.getElementById('snum').value);
      let result = fnum * snum;
      document.getElementById('result').innerHTML = result;}
   function div(){
      let fnum = parseInt(document.getElementById('fnum').value);
      let snum = parseInt(document.getElementById('snum').value);
      let result = fnum / snum;
      document.getElementById('result').innerHTML = result;}
      </script>
 
 
</head>
<body>

  <input type="text" id="fnum" value="20">&nbsp&nbsp
  <input type="text" id="snum" value="10">
  <hr>
  <input type="button" value="+" onclick ="add()"/>&nbsp&nbsp
  <input type="button" value="-" onclick ="sub()"/>&nbsp&nbsp
  <input type="button" value="*" onclick ="mul()"/>&nbsp&nbsp
  <input type="button" value="/" onclick ="div()"/>
  <hr>
  result =
  <h3 id="result">  </h3>

</body>
 // 콜백함수 callback function
    // 다른 함수의 인수로 사용하는 함수를 말한다.
 
 
<body>
  <button onclick = "alert('버튼클릭')">인라인 - 클릭</button>
  <button onclick = "display()">함수호출 - 클릭</button>
  <button id="callback">콜백함수 - 클릭</button>
  <button id="arrow">화살표함수 - 클릭</button>


  <script>
    // 콜백함수 callback function
    // 다른 함수의 인수로 사용하는 함수를 말한다.
    function display(){
      alert("버튼을 클릭했습니다")
    }
    const btn = document.querySelector('#callback');
    btn.addEventListener('click', display);

    const btn1 = document.querySelector('#arrow');
    btn1.addEventListener('click', () => alert("화살표함수-클릭"));

    // btn1. addEbentListener('click', function(){alert("화살표함수-클릭")})
    // btn1. addEbentListener('click', () = > alert("화살표함수-클릭"))

    function fn01(name, age){
      alert(`안녕하세요? ${name}님, 나이가 ${age} 살이시군요`)
    }
    function getInfo(aaa){
      let userName = "홍길동";
      let userAge = 1000;
      aaa(userName, userAge);
    }
     getInfo(fn01);
  </script>
</body>
<script>
    /*
      1급 함수(1급시민, first-class citizen)의 조건

      1. 변수에 할당할 수 있어야 한다.
      2. 다른 함수의 인자값으로 전달할 수 있어야 한다,
      3. 다른 함수에서 return값으로 함수결과를 반환할 수 있어야 한다.

    */
   let fn01 = function(){}
   function fn02(fn01){ fn01();}  

   // 세 번째 조건
   function fn03(){
    return function(a, b){
      return null
    }
   }

   // a 값이 b 값보다 크면 a-b, 작으면 b-a 결과를 리턴하는
   // 세번째 조건을 만족하는 함수 만들기
   
   let init = () => {
    return function(a,b){
      return a-b > 0 ? a-b : b-a;

    }
   }
   console.log(`1. init() ${init()}`);
   console.log(`2. init(20, 10) ${init(20, 10)}`);
   console.log(`3. init()() ${init()()}`);
   console.log(`4. init()(20, 10) ${init()(20, 10)}`);

  </script>
<script>
    /*
      내장함수(builtin function) : JavaScript에서 기본적으로 제공(내장)되는 함수를 말한다.

      1. Timer함수 : 특정 시간에 특정 함수(콜백함수)를 실행할 수 있게 해주는 함수.
       1) setTimeout(콜백함수, ms) : 지정된 시간(ms)에 정의된 콜백함수를 1번만 실행
       2) setInterval(콜백함수, ms) : 일정한 시간(ms)마다 정의된 콜백함수를 반복해서 실행
       3) clearInterval(id) : setInterval에서 정의된 콜백함수를 반복하는 것을 중지
       4) clearTimeout(id) : setTimeout에 정의된 콜백함수를 실행하는 것을 중지

      2. 자주쓰이는 함수 : Object, Number, String, Array, Date, Math, JSON ....
      3. 숫자확인함수 :
        isNaN() : number가 NaN인지 여부를 true, false로 리턴
        isFinite() : number가 무한값인 여부
        ...예를 들어 1 / 0의 결과는 대부분의 프로그램언어에서는 에러가 발생하고
        프로그램ㅇ ㅣ중단되지만 JavaScript은 infinity라는 값이 저장된다.

    */

    // 크롬에서 실행 - 1초마다 콜백함수를 실행하기
      var intervalID = setInterval (function(){
      document.write('<h6>' + new Date() + '</h6>');// 대문자 'Date'는 생성자 함수
    }, 1000); // 1000ms = 1초
     
    // 5초 후에 함수를 1번만 실행
    setTimeout(function() {
      clearInterval(intervalID);
    }, 5000);


    let number = 1 / 0;
    document.write (`0으로 나눌 때의 결과 = ${number}<br>`);
    document.write (`0으로 나눌 때의 결과 = ${isFinite(number)}<br>`);

    // function date(){}
    // class Date() {}
    // constructor Date(){}

     
     
  </script>
 <script>
    /* 생성자함수
      1. new 연산자로 객체를 생성할 수 있는 함수
      2. 생성자함수명은 첫글자는 대문자로 시작하고 카멜케이스를 준수하는 것이 관례이다.
      3. 일반함수와 생성자함수를 구분하는 방법은 return문의 유무로 구분한다.
         즉, return문이 없고 대문자로 시작하면 생성자함수로 정의한다.
    */
   function Student() {} //생성자함수
   function student() { return } //일반함수

   let std1 = new Student();
   let std2 = new student();
   let std3 = Student();

   
   // new.target으로 new로 생성되었는 지 아니면 객체리터럴 {} 생성되었는지 확인을 true, false로 리턴

   document.write(typeof std1, '<br>');
   document.write(typeof std2, '<br>');
   document.write(typeof std3, '<br>');

   // 생성자 함수
   function Student(name, kor, eng, mat) {
    this.name = name;
    this.kor = kor;
    this.eng = eng;
    this.mat = mat;
   
    // this.getSum = () => this.kor + this.eng + this.mat;
    this.getAvg = () => this.getSum() / 3;
   
  }

   // 객체의 공통영역(Prototype)
   // JavaScript에서 모든 함수는 공통영역인 prototype영역이 있다.
   // 공통영역을 정의하는 방법은
   // 1. 속성 : 생성자함수.prototype.속성명 = 값
   // 2. 매서드 : 생성자함수.prototype.매서드명 (대표적 toString)
   Student.prototype.nation = '대한민국';
   Student.prototype.toString = function() {
    return `나의 이름은 ${this.name}입니다`;
   }
    Student.prototype.getSum = function() { return this.kor + this.eng + this.mat };
    Student.prototype.getAvg = function() { return this.getSum() / 3; }

   let hong = new Student('홍길동', 99,98,97);
   let sonny = new Student('손흥민', 99,98,97);

   document.write(`${hong.name}의 총점은 ${hong.getSum()}, 평균은 ${hong.getAvg()}입니다<br>`)
   document.write(`${sonny.name}의 총점은 ${sonny.getSum()}, 평균은 ${sonny.getAvg()}입니다<br>`)
  </script>
<script>
    /*
      자바스크립트에서 객체를 만드는 방법이 객체리터럴{}, new 객체생성연산자(생성자함수),
      \Object(), object.create() 4가지 방법이 있다. 그 중 객체 리터럴과
      new연산자로 객체를 생성한다.

      객체리터럴과 생성자 함수는 기술적으로 차이는 없지만 생성자 함수명은
      대문자로 시작하는 것이 관례이고, new라는 객체생성연산자로만 생성할 수 있다.

    */
   let hong1 = {
    name: '홍길동',
    age: 1000
   }
   let hong2 = {
    name: '홍길순',
    age: 900,
    sayHello: function(){ console.log(`안녕하세요 저는 ${this.name}입니다`)}
   }

   function Hong(name,age){
    this.name = name;
    this.age = age;
    this.sayHello = function(){ console.log(`안녕하세요 저는 ${this.name}입니다`)};
   }

   let hong3 = new Hong('홍길성', 800);
   let hong4 = new Hong('홍길자', 700);
   let hong5 = new Hong('홍길상', 600);

   console.log(hong1.name, hong1.age);
   console.log(hong2.name, hong2.age);
   console.log(hong3.name, hong3.age);
   console.log(hong4.name, hong4.age);
   console.log(hong5.name, hong5.age);

 

  </script>
<script>
    /*
      화살표 함수 (Arrow Function)
      1. 매개변수의 유무
    */
   // 1. 매개변수가 없을 경우
   let hi = function(){
    return '안녕하세요(1)?';
   }
    hi = () => { return '안녕하세요(2)'};
    hi = () => { '안녕하세요(3)' };
    hi = () =>  '안녕하세요(4)' ;
    console.log(hi());


    // 2. 매개변수가 하나만 있을 경우
    let sayHello = function(name) {return name + '님 안녕하세요?'}

    sayHello = (name) => {return name + '님 안녕하세요(2)?'}
    sayHello = name => {return`${name}님 안녕하세요(3)?`}
    console.log(sayHello('홍길동'));

    // 3. 매개변수가 한개이상 있을 경우
    let 더하기 = function add(a,b){return a + b}
    더하기 = (a, b) => a + b;
    console.log(더하기(10,10));
  </script>

디지털시계.html

  <style>
    .clock{
      width : 200px;
      height : 100px;
      text-align : center;
      color : #f4f4f4;
      background-color: black;
    }
    #clock{color:#f0c420;
    font-size : 20px;
  }
    #clockday{
      color:mediumaquamarine;
      font-size: 0.5em;
    }

  </style>
</head>
<body>
  <div class="clock">
    <div id="clock">00:00</div>
    <div id="clockday">00/00/00</div>
  </div>
 
  <script>
    function Clock(){

      let date = new Date();
      let YYYY = String(date.getFullYear());
      let MM = String(date.getMonth());
      let DD = String(date.getDate());
      let hh = String(date.getHours());
      let mm = String(date.getMinutes());
      let ss = String(date.getSeconds());
      let Week = Weekday();

  // 출력함수호출
    Write(YYYY, MM, DD, hh, mm, ss, Week);

    //요일을 리턴해주는 함수
    function Weekday() {
      let Week = ['일', '월', '화', '수', '목','금', '토' ];
      let Weekday = date.getDay();
      return Week[Weekday];
 
    }

    //0을 채워주는 함수 : 1의 자리수가 나올 때 0을 채우는 함수
    function Zero(num){
      return (num <10? '0'+num : '' + num);
    }

    //날짜와 시간을 출력해주는 함수
    function Write(YYYY, MM, DD, hh, mm, ss, Week){
      let ClockDay = document.getElementById('clockday');
      let Clock = document.getElementById('clock');
      ClockDay.innerText = YYYY + '.' +  MM + '.' + DD + `${Week}요일`;
      Clock.innerText = `${hh}:${mm}:${ss}`;
    }

   
    }
    setInterval(Clock, 1000);
  </script>
</body>

' > javascript' 카테고리의 다른 글

js06_BOM  (0) 2023.05.31
js05_object  (0) 2023.05.31
js03_for  (0) 2023.05.31
js02_if  (0) 2023.05.31
js01_변수  (0) 2023.05.31