Learn & Record

Html Css JavaScript (rest parameter, 전개연산자, 재귀함수, 콜백함수, map, filter, 화살표함수, timer, 연습문제) 본문

Dev/HTML CSS JS

Html Css JavaScript (rest parameter, 전개연산자, 재귀함수, 콜백함수, map, filter, 화살표함수, timer, 연습문제)

Walker_ 2024. 3. 29. 15:50

1. 나머지 매개변수 rest parameter

/*
나머지 매개변수 : rest parameter
가변 매개변수 함수 : 호출할 때 매개변수의 갯수가 고정적이지 않는 함수
 */

 - 자바 스크립트에서는 이러한 함수를 구현할 때 '나머지 매개변수'를 사용

 - 함수 매개변수 앞에 마침표 3개(...)를 입력하면 매개변수가 배열로 들어옴

function sample(...items) {
    console.log(items);
}
sample(1,2); // [1,2]
sample(1,2,3); // [1,2,3]
sample(1,2,3,4); // [1,2,3,4]

function sample2nd(items) {
    console.log(items)
}
sample2nd([1,2])
sample2nd([1,2,3])
sample2nd([1,2,3,4])

 

 - 나머지 매개변수를 사용하는 min 함수

<script>
    /*
    나머지 매개변수를 사용하는 min 함수
     */
    const min = function (...array) {
        let min = array[0];
        for (let i =1; i < array.length; i++) { // 0번 인덱스를 초기화에 사용했으니 1번 인덱스부터 사용
            if (min > array[i]) { // 현재 min 보다 더 작다면
                min = array[i]; // min 값을 변경
            }
        }
        return min;
    }

    console.log(`[52, 273, 32, 103, 275, 24, 57]중에서`)
    console.log(`최솟값 = ${min(52, 273, 32, 103, 275, 24, 57)}`);
</script>

 

 - 나머지 매개변수와 일반 매개변수 조합하기

<script>
    /*
        기본형
        function 함수명 (매개변수, 매개변수, ...나머지 매개변수) { }
     */
    function sample(a, b, ...c) {
        console.log(a, b, c);

    }
    // 매개변수 a,b가 먼저 들어가고, 남은 것은 모두 c에 배열 형태로 들어감
    sample(1, 2); // 1, 2 []
    sample(1, 2, 3); // 1, 2 [3]
    sample(1, 2, 3, 4); // 1, 2 [3, 4]
</script>

 

-

나머지 매개 변수와 일반 매개변수 조합하기
매개변수의 자료형에 따라 다르게 작동하는 함수 만들기

조건
1) min(배열) : 매개 변수에 배열을 넣으면 배열 내부에서 최솟값을 찾아주는 함수
2) min(숫자, 숫자) : 매개변수에 숫자를 넣으면 숫자들 중 최솟값을 찾아주는 함수
 

 

2. 전개 연산자 spread operator

 - 배열을 전개해서 함수의 매개 벼수로 전달

 - 전개 연산자는 일바적으로 1) 함수 호출시 2) 배열 앞에 마침표 3개를 붙이는 형태로 나옴

<script>
    /*
    기본형: 함수 호출시
    함수이름(...배열)
     */
    'use strict';
    const array = [1,2,3,4]

    // 기본적인 전개 연산자 사용법
    // 1)인수로 전달
    function sample1st(a,b,c) {
        console.log('sample1st() 실행')
        console.log(a, b, c, d)
    }

    // 전개 연산자를 이용해서 배열을 인수로 전달
    // 배열은 개개로 전개해서 전달한 것과 결과가 같음
    sample1st(...array);
    sample1st(array[0]. array[1], array[2], array[3])

    // 2) 함수의 리턴 값  배열로 하고 결과 값을 전개 전달

    function sample2nd() {
        console.log('sample2nd() 실행')
        let array = [1, 2, 3, 4]
        return array;
    }
    console.log(sample2nd()) // [1,2,3,4]. 결과 값은 배열
    let [a,b,c,d] = sample2nd();
    console.log(a); //1

    // 2. 나머지 매개 변수와 함께 사용하는 경우
    function sample3rd(...items) { // 단순하게 매개변수를 모두 출력하는 함수
       document.write('<br>sample3rd() 실행<br>');
       document.write(items, '<br>');
       for (const item of items) {
           document.write(item, '<br>')
       }
    }

    console.log('# 전개 연산자를 사용하지 않을 경우');
    sample3rd(array); // 배열의 요소로 배열을 가진 매개변수가 됨
    console.log('# 전개 연산자를 사용한 경우')
    sample3rd(...array);

    // 3. 일반 매개변수에 전개 연산자 사용
    function sample4th(items) {
        document.write('<br>sample4th() 실행<br>');
        document.write(items, '<br>');
        for (const item of items) {
            document.write(item, '<br>');
        }
    }
    // 전개 되어서 전달이 됨. sample4th(1, 2, 3, 4)과 동일한 결과.
    // items에 1만 전달이 되고, 배열이 아니기 때문에 for문으로 순회가 안됨
    sample4th(array);
    sample4th(...array); // 1. Uncaught TypeError: items is not iterable at sample4th()
    sample4th(1, 2, 3, 4); // 1. Uncaught TypeError: items is not iterable at sample4th()

    console.log(sample2nd())

    sample1st(array[0], array[1], array[2])
</script>

 

3. 재귀함수

 - 함수 정의문 내에서 작성한 코드로 함수를 다시 호출하는 것

<script>
     let num = 0;
     function testFnc() {
         // 재귀 함수 호출을 적용하여 1부터 10까지의 값을 출력
         num++;
         document.write(num, '<br>');

         if(num === 10) return; // num 값이 10이면 종료

         console.log(`${num} 번째 호출`);
         testFnc(); // 재귀 함수 호출
     }
     testFnc();
</script>

 

4. 콜백 함수 collback function

 - 매개 변수로 전달하는 함수. 자바 스크립트는 함수도 하나의 자료형이므로 매개변수로 전달 할 수 있음

<script>
    function callThreeTimes (callback) {
        for (let i =0; i < 3; i++) {
            callback(i);
        }
    }

    function print(i) {
        console.log(`${i}번째 함수 호출`);
    }

    // 함수를 호출.
    callThreeTimes(print);

</script>

 

5.콜백함수로 익명함수 사용하기

<script>
    function callThreetimes (callback) {
        for (let i = 0; i < 3; i++) {
            callback(i);
        }
    }

    // 함수들 호출. 다른 언어에서는 낯선 방법이나 자바 스크립트나 코틀린 같은 이벤트 기반을 프로그래밍에서는 자주 사용
    callThreetimes(function (i) {
        console.log(`${i}번째 함수 호출하기`)
    });
</script>

 

 - 콜백함수를 활용하는 함수 : forEach() 메서드

 - 배열이 갖고 있는 함수(메서드)로써 단순하게 배열 내부 요소를 사용해서 콜백함수를 호출

 - 배열이 가지고 있는 메소드 중 콜백 함수를 활용하는 메서드는 아래와 같은 형태의 콜백함수를 사용

 - 매개 변수가 다 필요하지 않음

/*
기본형:
function (value, index, array) { }
 */

 

const numbers = [273, 52, 103, 32, 57]

number.forEach(function (value, index, array) {
    // 매개변수로 value, index, array를 갖는 콜백함수를 사용
    console.log(`${index}번째 요소 : ${value}`)
});

// 함수 선언한 후에 매개 변수로 넘겨도 됨
const call = function (value, index, array) {
    // 매개변수로 value, index, array를 갖는 콜백함수를 사용
    console.log(`${index}번째 요소 : ${value}`)
}
numbers.forEach(call);

number.forEach(function (v, i) { // 매개변수로 v, i만 사용
    console.log(`${i}번째 요소 : ${v}`)
});

 

6. map() 맵

<script>

    // map() 메서드
    // 배열이 가지고 있는 메서드
    // 콜백함수에서 리턴한 값들을 기반으로 새로운 배열을 만들고 '배열 리턴'

    // 배열을 선언
    let numbers = [273, 52, 103, 32, 57]

    // 배열의 모든 값을 제곱
    let numbers2 = numbers.map(function(value, index, array) {
        return value * value;
    })
    console.log(numbers2); // (5) [74529, 2704, 10609, 1024, 3249]

    // 출력
    numbers2.forEach(console.log); // value, index, array 순서대로 출력

    let numbers3 =[];
    for (i=0; i<numbers.length; i++) {
        numbers3.push(numbers[i] * numbers[i])
    }
    console.log(numbers3)

    
    for (const item of numbers) {
        numbers4.push(item * item)
    }

</script>

 

7. 필터 filter()

 - 콜백함수를 활용하는 함수 : filter()

 - 콜백함수에서 리턴하는 값이 true인 것들만 모아서 새로운 배열을 만듬

 - 콜백함수의 리턴 타입이 불 형 이어야 함

<script>

    // filter() 메서드

    const numbers = [11,12,13,14,15,16]

    // 짝수만 추출
    const evenNumbers = numbers.filter(function (value) {
        return value % 2 === 0;
    });

    // 인덱스가 짝수만 추출
    const evenIndexs = numbers.filter(function (value, index) {
        return index % 2 ===0;
    });

    console.log(`원래 배열: ${numbers}`) // 원래 배열 : 11, 12, 13, 14, 15, 16
    console.log(`값이 짝수만 추출 : ${evenNumbers}`) // 12, 14, 16
    console.log(`인덱스가 짝수만 추출 : ${evenIndexs}`) // 11, 13, 15

    // 1의 자리가 3의 배수인 경우만 추출 > 13, 16
    const evenOneThree = numbers.filter(function (value) {
        return value % 10 % 3 === 0;
    })

    console.log(`1의 자리가 3의 배수인 경우만 추출 : ${evenOneThree}`)

</script>

 

8. 화살표 함수 Arrow function

 - ES6에 추가된 내용으로 '=>'를 이용하여 함수를 간결하게 표현할 때 사용

 - 1) function 키워드를 생략하고

 - 2) 부등호 '='과 '>'를 합쳐서 코딩하고

 - 3) 항상 익명함수 형식으로 표현

 - 4) 단일 명령문일 경우 함수의 중괄호 {} 와 return을 생략

<script>
    // 화살표 함수

    const doAddtion1 = function(s1, s2) {
        return (s1 + s2) / 2;
    }
    console.log(doAddtion1(2,5)); // 3.5

    const doAddtion1 = (s1, s2) => {
        return (s1 + s2) / 2;
    }
    console.log(doAddtion1(2,5)); // 3.5

    const doAddtion1 = (s1, s2) => (s1 + s2) / 2;
    console.log(doAddtion1(2,5)); // 3.5
    
</script>

 

 - map(), filter() 함수처럼 단순한 형태의 콜백 함수를 쉽게 입력

 - function 키워드 대신 화살표(=>)를 사용

<script>
    // 화살표 함수2
    /*
    기본형 :
    (매개변수) => { }
     */
    let numbers = [0,1,2,3,4,5,6,7,8,9];

    // numbers에서 2의 배수만 추출한 후, 제곱을 한 후에 로그에 출력.

    // 배열의 메소드를 연속적으로 사용. 메소드 체이닝.
    // 메소드 체이닝 : 메소드가 리턴하는 값을 기반으로 해서 메서드를 줄줄이 사용하는 것

    numbers.filter((value) => value % 2 === 0) // 2의 배수만 추출 / [0, 2, 4, 6, 8]
        .map((value) => value * value) // 제곱 / [0, 4, 16, 36, 64]
        .forEach((value) => console.log(value)); // [0, 4, 16, 36, 64]

</script>

 

9. 타이머 함수 timer

 -  특정 시간 이후에 콜백함수를 호출할 수 있는 함수

 -  setTimeout(함수, 시간) : 특정 시간 후에 함수를 한 번 호출

 - setInterval(함수, 시간) : 특정 시간마다 함수를 호출

 

<script>
    setTimeout(function (){
        console.log('2초 후에 실행됩니다.')
    }, 2 * 1000); // (2 * 1000) = 2초. 시간의 기초단위는 밀리 초 단위.

    let count = 0;
    console.log(timer.textContent);
    setInterval(() => {
        
    }, 1*1000);

</script>

 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        div {
            width: 100vw;
            height: 10vh;
            display: flex;
            justify-content: center;
            align-content: center;
            font-size: 300px;
        }
    </style>
    <script>
        // 1초씩 올라가는 색깔 변하는 카운트
        
        const rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
        let count = 1;
        setInterval(function () {
            document.querySelector('div').innerHTML = String(count);
            document.querySelector('div').style.color = rainbow[count % rainbow.length]
            count++;
        }, 1* 1000);
    </script>
</head>
<body>
    <div>0</div>
</body>
</html>

 

 - 타이머 함수 : 타이머를 종료하고 싶을 때

 - clearTimeout(타이머_ID) : setTimeout() 함수로 설정한 타이머를 제거

 - clearIntreval(타이머_ID) : setInerver() 함수로 설정한 타이머를 제거

<script>

    let count = 0;
    let oneRun = setInterval(() => {
        console.log(`1초마다 실행됩니다(${count}번째)`)
        count++;
    }, 1 * 1000);

    setTimeout(() => {
        console.log('타이머를 종료합니다.')
        clearInterval(oneRun);
    }, 5 * 1000); // 5초후 종료
</script>

 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        div {
            width: 100vw;
            height: 60vh;
            display: flex;
            justify-content: center;
            align-content: center;
            font-size: 300px;
        }
        span {
            width: 200px;
            height: 100px;
            display: block;
            margin: 0 auto;
            color: #00bbdd;
            background-color: #fafafa;
            border: none;
            border-radius: 30px;
            font-size: 30px;
            cursor: pointer;
            text-align: center;
        }
    </style>
    <script>
        // 1초씩 올라가는 색깔 변하는 카운트

        const rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
        let count = 1;
        const timeCount = setInterval(function () {
            document.querySelector('div').innerHTML = String(count);
            document.querySelector('div').style.color = rainbow[count % rainbow.length]
            count++;
        }, 1* 1000);

         // 카운팅 종료
        function timeStop() {
            clearInterval(timeCount)
        }

    </script>
</head>
<body>
    <div>0</div>
    <span onclick="timeStop()">STOP</span>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        div {
            width: 100vw;
            height: 60vh;
            display: flex;
            justify-content: center;
            align-content: center;
            font-size: 300px;
        }
        span {
            width: 200px;
            height: 100px;
            display: block;
            margin: 0 auto;
            color: #00bbdd;
            background-color: #fafafa;
            border: none;
            border-radius: 30px;
            font-size: 30px;
            cursor: pointer;
            text-align: center;
        }
    </style>
    <script>
        // 1초씩 올라가는 색깔 변하는 카운트

        const rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
        let count = 1;
        const timer = function () {
            document.querySelector('div').innerHTML = String(count);
            document.querySelector('div').style.color = rainbow[count % rainbow.length]
            count++;
        };

        let id = setInterval(timer, 1*1000)
         // 카운팅 종료
        const stopTimer = function () {
            clearInterval(id)
        }
        // 카운팅 재시작
        const restartTimer = function ()  {
            id = setInterval(timer, 1 * 1000)
        }


    </script>
</head>
<body>
    <div>0</div>
    <span onclick="stopTimer()">STOP</span>
    <span onclick="restartTimer()">RE START</span>
</body>
</html>

 


공부 과정을 정리한 것이라 내용이 부족할 수 있습니다.

부족한 내용은 추가 자료들로 보충해주시면 좋을 것 같습니다.

읽어주셔서 감사합니다 :)