생각기록

생활 코딩 WEB2 JavaScript 4 본문

강의 정리/생활 코딩 강의 정리

생활 코딩 WEB2 JavaScript 4

끼록관 2022. 11. 11. 16:46

배열과 반복문의 활용

 

콘솔에 찍힌 a태그 배열들을 반복문에 활용해보기

 

이런식으로 응용이 가능하다

 

함수

만약

위의 파우더블루가 1억개라면..

그걸 골라 낼 수 있게 해주는게 함수!

 

함수로 웹페이지의 크기가 극단적으로 줄어들 수 있다!

밑의 코드 수정 요망!

<!DOCTYPE html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="button" value="night" onclick="nightDayHandler(this)">
    <input type="button" value="day" onclick="nightDayHandler(this)">
        <a href="#">2</a>
        <a href="#">3</a>
        <a href="#">4</a>
</body>
<script>

    function nightDayHandler(self){
        if (self.value === 'night'){
        var target = document.querySelector('body');
        target.style.backgroundColor = 'black';
        target.style.color = 'white';
        self.value = 'day';

        var alist = document.querySelectorAll('a');
        var i = 0;
        while( i < alist.length ){
        alist[i].style.color = 'powderblue';
        i = i + 1; }

        } else {
        target.style.backgroundColor = 'white';
        target.style.color = 'black';
        self.value = 'night';

        var alist = document.querySelectorAll('a');
        var i = 0;
        while( i < alist.length ) {
            alist[i].style.color = 'blue';
            i = i + 1;
        }
        }
    }
</script>
</html>

 

함수의 이론

  • 기본적 문법 Basic
  • Parameter  & Argument
  • Return

항상 극단적으로 생각해라 

이 두개의 반복이 1억번 해야 한다면?

그리고 연속적이지 않다면, 반복문은 불가능하다.

그럴 때 필요한게 함수이다.

이것을 반복 하고 싶다.

1. 반복 하고 싶은 것을 보기

2. 이 내용을 함수선언에 넣고, 반복될 부위에 two(); 함수 실행!

= 기본 함수 문법

    <h1>function</h1>
    <h2>Basic</h2>
    <ul>
        <script>
         function two(){
            document.write('<li>2-1</li>');
            document.write('<li>2-2</li>');
         } 
        //  반복 될 곳에 함수실행 삽입
            document.write('<li>1</li>');
            two();
            document.write('<li>3</li>');
            two();
        </script>
    </ul>
    <h2>Parameter & Argument</h2>
    <h2>Return</h2>

함수는 음료 자판기

제품 선택(입력)

제품 제공(출력)

입력과 출력으로 이루어져 있다.

입력과 출력은 수학적으로 함수이다.

 

  • 입력 - parameter,  Argument  (매개변수, 인자)
  • 출력 - return (출력)
    <h2>Parameter & Argument</h2>
    <script>
        function onePlusone(){
            document.write(1+1);
        }//값이 변하지 않는 위, 상황에 따라 달라지는 sum 만들어보자
        function sum(left, right){  
            document.write(left + right + '<br>');
        }//left, right 매개 변수
        sum(2,3); // 5   인자 2,3
        sum(3,4); // 7
    </script>

밑에서는 left, light가 매개 변수

sum( 2, 3); 2와 3이 인자이다.

 

  1. 어떤 결과를 어떤식으로 도출하고 싶은지? 먼저 생각해보자
  2. sum(2,3)을 더해서 5가 나오도록 해보자 ! 그러려면 ?
  3. function sum(left, right)  2와 3의 인자들이 들어갈 자리의 매개변수를 만든다.
  4. 매개 변수를 이용한 식을 만든다.

 

return

표현식이란

위의 사진에서 2에 대한 표현식은 1+1 이다.

함수도 이런식으로 생각하면 된다!

 

더해진 결과를 다양한 방법으로 사용해야 한다면? (ex)색을 바꿔야한다.

    <h2>Return</h2>
    <script>
        function sum2(left, right){
            return left+right;
        }
        document.write(sum2(2,3)+'<br>'); //5가 나오도록
        document.write('<div style="color:red;">'+sum2(2,3)+'</div><br>');
        document.write('<div style="font-size:3rem;">'+sum2(2,3)+'</div><br>');
    </script>

함수의 매개 변수들의 연산 값을 return 출력한다.

계산이라는 기능만을 sum2가 구현할 때, 다양한 맥락에서 활용 가능하게 하는 것이 return이다.

 


리팩토링 예시

함수

 

1억개의 버튼에  밑의 사진 기능을 넣어보자

    <script>
    function nightDayHandler(self){
        var target = document.querySelector('body');
        if (self.value === 'night'){
        target.style.backgroundColor = 'black';
        target.style.color = 'white';
        self.value = 'day';

        var alist = document.querySelectorAll('a');
        var i = 0;
        while( i < alist.length ){
        alist[i].style.color = 'powderblue';
        i = i + 1; }

        } else {
        target.style.backgroundColor = 'white';
        target.style.color = 'black';
        self.value = 'night';

        var alist = document.querySelectorAll('a');
        var i = 0;
        while( i < alist.length ){
            alist[i].style.color = 'blue';
            i = i + 1;
            }
        }
    }
    </script>
</head>
<body>
    <input type="button" value="night" onclick="nightDayHandler(this)">
    <input type="button" value="day" onclick="nightDayHandler(this)">
        <a href="#">2</a>
        <a href="#">3</a>
        <a href="#">4</a>
</body>

1억개의 버튼에 일일이 밑의 기능을 추가 하지 않아도

각각의 버튼에 함수를 호출하면, 훨씬 간결하다.