KIC/JavaScript,CSS

day38 - JavaScript(prompt, for문, while, 이중 for문, function, array, parameter, callback)

바차 2021. 8. 6. 16:34
반응형

[prompt]

<!DOCTYPE html>
<html>

<head>
    <meta charset="EUC-KR">
    <title></title>
    <script>
        //입력시 문자열이므로 Number를 통해 숫자로 변환
        // 변수 한글로 가능
        const 입력 = prompt('정수를 입력해 주세요.', '')
        const 숫자 = Number(입력)

        // 타입까지 모두 같을 경우 = 3개
        if (숫자 % 2 === 0) {
            alert(`${입력}은 짝수입니다.`)
        } else {
            alert(`${입력}은 홀수입니다.`)
        }


        const rawInput = prompt('태어난 해를 입력하시오.', '')
        const year = Number(rawInput)

        //순서가 원숭이 띠부터 여야 제대로 작동하는 듯 하다.
        const tti = '원숭이, 닭, 개, 돼지, 쥐, 소, 호랑이, 토끼, 용, 뱀, 말, 양'.split(',')

        //``(백틱) 을 써야 입력값 출력 가능
        alert(`${year}년에 태어났다면 ${tti[year % 12]}띠 입니다.`)

    </script>
</head>

<body>
</body>

</html>

 

 

 

[for문 예제]

<!DOCTYPE html>
<html>

<head>
    <meta charset="EUC-KR">
    <title></title>
    <script>
        //입력시 문자열이므로 Number를 통해 숫자로 변환
        // 변수 한글로 가능
        const todos = ['업무 1', '업무 2', '업무 3']

        // 지금은 0부터 시작이지만
        //초기값을 1로 주고 시작하면 '1번째' 부터 시작 가능

        // 블럭 안에서 const i를 반복해서 새롭게 잡는 느낌이므로 const 상수로 선언해도 상관 없다.
        for (const i in todos) {
            console.log(`${i}번째 할 일: ${todos[i]}`)
        }

        for (const todo of todos) {
            console.log(`오늘의 할 일: ${todo}`)
        }

    </script>
</head>

<body>
</body>

</html>

 

 

[while]

<!DOCTYPE html>
<html>

<head>
    <meta charset="EUC-KR">
    <title></title>
    <script>

        let i = 0
        while (confirm('계속 진행 하시겠습니까?')) {
            alert(`${i}번째 반복입니다.`)
            i = i + 1
        }

        i = 0
        const array = [1, 2, 3, 4, 5]
        while (i < array.length) {
            console.log(`${i} : ${array[i]}`)
            i++
        }


    </script>
</head>

<body>
</body>

</html>

 

[이중 for문]

<!DOCTYPE html>
<html>

<head>
    <meta charset="EUC-KR">
    <title></title>
    <script>

        let output = ''
        for (let i = 1; i < 15; i++) {
            for (let j = 15; j > i; j--) {
                output += ' '
            }
            for (let k = 0; k < 2 * i - 1; k++) {
                output += '*'
            }
            output += '\n'
        }

        //출력
        console.log(output)


    </script>
</head>

<body>
</body>

</html>

 

 

 

[function 예제]

<!DOCTYPE html>
<html>

<head>
    <meta charset="EUC-KR">
    <title></title>
    <script>
        //변수 선언 후 익명 함수 저장
        const 함수 = function () {
            console.log('함수 내부의 코드입니다 ... 1')
            console.log('함수 내부의 코드입니다 ... 2')
            console.log('함수 내부의 코드입니다 ... 3')
            console.log('')
        }

        // 선언적 함수
        // function 함수() {
        //     console.log('함수 내부의 코드입니다 ... 1')
        //     console.log('함수 내부의 코드입니다 ... 2')
        //     console.log('함수 내부의 코드입니다 ... 3')
        //     console.log('')
        // }

        //함수 호출
        함수()
        함수()

        //출력
        console.log(typeof 함수)
        console.log(함수)

        function f(x) {
            return x * x
        }

        console.log(f(3))

    </script>
</head>

<body>
</body>

</html>

 

 

-> 한글로 변수나 함수를 선언하는 것은 가능하지만 추천하진 않는다고 한다.

 

 

[array 예제]

<!DOCTYPE html>
<html>

<head>
    <meta charset="EUC-KR">
    <title></title>
    <script>

        function min(array) {
            let output = array[0]
            for (const item of array) {
                // 현재 output 보다 더 작은 item 이 있다면
                if (output > item) {
                    //output 값으로 변경
                    output = item
                }
            }
            return output
        }

        const testArray = [52, 273, 32, 103, 275, 24, 57]
        console.log(`${testArray}중에서 `)
        console.log(`최솟값 = ${min(testArray)}`)


    </script>
</head>

<body>
</body>

</html>

 

 

 

[array2]

<!DOCTYPE html>
<html>

<head>
    <meta charset="EUC-KR">
    <title></title>
    <script>

        function min(...items) {
            //매개변수 items는 배열처럼 사용한다.
            let output = items[0]
            for (const item of items) {
                // 현재 output 보다 더 작은 item 이 있다면
                if (output > item) {
                    //output 값으로 변경
                    output = item
                }
            }
            return output
        }


        // 함수를 이름만 선언 해놓고 arguments 예약어로 파라미터를 받아올 수 있다.
        function min2() {
            let output = arguments[0]
            for (const item of arguments) {
                // 현재 output 보다 더 작은 item 이 있다면
                if (output > item) {
                    //output 값으로 변경
                    output = item
                }
            }
            return output
        }

        console.log('min(52, 273, 32, 103, 275, 24, 57)')
        console.log(`= ${min(52, 273, 32, 103, 275, 24, 57)}`)

        //위와 같은 결과를 출력한다.
        console.log('min2(52, 273, 32, 103, 275, 24, 57)')
        console.log(`= ${min2(52, 273, 32, 103, 275, 24, 57)}`)


    </script>
</head>

<body>
</body>

</html>

 

 

 

 

 

[parameter]

...c -> 전개 연산자 사용: 가변형 배열 생성

<!DOCTYPE html>
<html>

<head>
    <meta charset="EUC-KR">
    <title></title>
    <script>
        
        // a, b 이후로는 배열로 받겠다는 의미
        function sample(a, b, ...c) {
            console.log(a, b, c) // a, b 는 변수, c는 배열로 출력
        }

        sample(1, 2)
        sample(1, 2, 3)
        sample(1, 2, 3, 4)


    </script>
</head>

<body>
</body>

</html>

 

 

[parameter2]

-> 전개 연산자 사용 유무

<!DOCTYPE html>
<html>

<head>
    <meta charset="EUC-KR">
    <title>Insert titlte here</title>
    <script>

        //단순하게 매개변수를 모두 출력하는 함수
        function sample(...items) {
            console.log(items)
        }


        //전개 연산자 사용 여부 비교하기
        const array = [1, 2, 3, 4]

        console.log('# 전개 연산자를 사용하지 않은 경우')
        sample(array)
        console.log('# 전개 연산자를 사용한 경우')
        sample(...array)



    </script>
</head>

<body>
</body>

</html>

 

 

 

[callback 함수]

-> 자바스크립트에서 함수는 object이다. 

 

-> 자바 스크립트의 함수는 다른 함수의 인자로 쓰일 수도, 어떤 함수에 의해 리턴될 수도 있다.

 

-> 이러한 함수를 고차 함수 라 부르고 인자로 넘겨지는 함수를 콜백 함수 라고 부른다.

<!DOCTYPE html>
<html>

<head>
    <meta charset="EUC-KR">
    <title></title>
    <script>
		
        //함수를 인자로 넘겨주기
        function callThreeTimes(callback) {
            for (let i = 0; i < 3; i++) {
                callback(i)
            }
        }
        function print(i) {
            console.log(`${i}번째 함수 호출`)
        }

        //함수를 호출한다.
        callThreeTimes(print)

    </script>
</head>

<body>
</body>

</html>

 

 

 

300x250