본문 바로가기
ICIA 수업일지

2021.07.23 수업일지

by 주성씨 2021. 7. 24.

- Java Script

- if review

<!DOCTYPE html>
<html lang="en">
<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>
    <script>
        // 참 : 0 아닌 값, 거짓 : 0 (C, C++, js)
        if(1){
            console.log("참");
        }
        if(-2){
            console.log("참");
        }
        if(0.1){
            console.log("참");
        }
        if("aa"){
            console.log("참");
        }
        if(0){
            console.log("0만 거짓");
        }
    </script>
</body>
</html>

 

- 함수 선언

        // 전역 변수
        var a=6, b=3;

        // 함수 선언
        // 자바스크립트는 void를 사용하지 않는다.
        function sum(){
            console.log(a+b);
        }
        function sub(){
            console.log(a-b);
        }
        // 함수 호출
        sum();
        sub();

 

        // 매개변수 사용
        // a, b 지역(매개) 변수 여기서만 사용. 나가면 stack에서 사라짐
        // 매개변수가 a,b만 있다면 a,b,c가 있다고 하더라도 필요한 a,b만 가져다 쓴다.
        function sum(a,b){
            console.log(a+b);
        }

        function sub(a,b){
            console.log(a-b);
        }
        sum(); // NaN ; Not a Number
        sub();

        sum(a,b);
        sub(a,b);

 

- 변수 (Variable), 변수의 유효범위(Variable Scope)

03_variable_scope

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>variable scope</title>
</head>

<body>
    <script>
        // 전역 변수 : 함수 외부에 선언
        // 자바의 필드값이랑 유사하다고 생각하면 된다.
        let a = 10,
            b = 20;
        // 지역변수 > 전역변수
        function fct1() {
            let a = 100,
                b = 100; //지역(local) 변수 : 함수 내부에서 선언
            console.log(a);
            console.log(b);
        }
        fct1();

        function fct2() {
            console.log(a);
            console.log(b);
        }
        fct2();

    </script>
</body>

</html>

https://www.educative.io/edpresso/what-is-the-let-keyword-in-javascript

※ let 과 var의 차이

 

What is the let keyword in JavaScript?

What is the let keyword in JavaScript?

www.educative.io

 

04_variable_scope2

- 호이스팅이란

자바스크립트 함수는 실행되기 전에 함수 안에 필요한 변수값들을 모두 모아서 유효 범위의 최상단에 선언한다.
자바스크립트 Parser가 함수 실행 전 해당 함수를 한 번 훑는다.
함수 안에 존재하는 변수/함수선언에 대한 정보를 기억하고 있다가 실행시킨다.
유효 범위: 함수 블록 {} 안에서 유효

- 호이스팅의 대상

var 변수 선언과 함수선언문에서만 호이스팅이 일어난다.
var 변수/함수의 선언만 위로 끌어 올려지며, 할당은 끌어 올려지지 않는다.
let/const 변수 선언과 함수표현식에서는 호이스팅이 발생하지 않는다.

 

- var를 사용할 경우

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>variable scope2</title>
</head>

<body>
    <script>
        var global = 100;

        function localFunc() {
            //지역변수에서 var를 생략하면 전역변수
            var local = 200; //이 함수 내에서만 사용 가능 한 지역 변수

            console.log(global);
            console.log(local);

            global = 300; //전역 변수 수정

            for (var i = 0; i <= 10; i++) { //i 는 for문 안에서 선언된 지역 변수 
                console.log("i : " + i);
            }
            console.log("i=" + i); //자바에서 에러이므로 주의!!!
        }

        function localFunc2() {

            console.log(global); //전역 변수는 어디서나 호출 가능하다.
            console.log(local); //호출한 변수는 현재 함수에 없으므로 에러가 난다.

        }

        localFunc();
        localFunc2();

    </script>
</body>

</html>

 

- let을 사용할 경우

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>variable scope2</title>
</head>

<body>
    <script>
        let global = 100;

        function localFunc() {
            //지역변수에서 var를 생략하면 전역변수
            let local = 200; //이 함수 내에서만 사용 가능 한 지역 변수

            console.log(global);
            console.log(local);

            global = 300; //전역 변수 수정

            for (let i = 0; i <= 10; i++) { //i 는 for문 안에서 선언된 지역 변수 
                console.log("i : " + i);
            }
            console.log("i=" + i); //자바에서 에러이므로 주의!!!
        }

        function localFunc2() {

            console.log(global); //전역 변수는 어디서나 호출 가능하다.
            console.log(local); //호출한 변수는 현재 함수에 없으므로 에러가 난다.

        }

        localFunc();
        localFunc2();

    </script>
</body>

</html>

 

05_variable_scope3

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>variable scope3</title>
</head>
<body>
    <script>
        showName();
        function showName(){
            let name="이도";
            console.log(name);
        }
        showName();
    </script>
</body>

ㄴ 펑션도 호이스팅이 된다.

 

06_loop&Array

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>loop & array</title>
</head>

<body>
    정수입력 : <input type="text" id="insert" placeholder="정수만"><br>
    <!-- text box에 입력하는 모든값은 문자열이다. -->
    <input type="button" value="insert" onclick="input()">

    <script>
        // 지속적인 작업을 위해서 전역변수로 선언
        let arr = [];
        let idx=0;
        function input() {
            // let arr=new Array();
            let txte = document.getElementById("insert");
            arr[idx]=parseInt(txte.value);
            idx++;
            console.log(parseInt(txte.value));
            for (let i = 0; i < arr.length; i++) {
                console.log(arr[i]);
            }
        }
    </script>
</body>

</html>

 

- 자료형 출력

        console.log(typeof 1);
        console.log(typeof 1.1);
        console.log(typeof 'a');
        console.log(typeof "a");
        console.log(typeof true);

 

- 재귀함수 ; 스스로가 스스로를 부르는 함수를 말한다.
팩토리얼 계산식으로 num은 함수안의 변수이므로 완전히 빠져나가기 전엔 stack에 계속 남아있다.
반복문으로 해결안되는 경우 재귀함수를 이용해서 푸는 경우도 있다.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <script>
        // 하노이탑, 피보나치 수열, 이진트리 검색
        let i = 0;
        function fct1() { // 재귀함수
            console.log('call' + i++);
            fct1(); // 재귀호출
        } // stackoverflow 발생
        fct1();
    </script>
</body>

</html>

 

- 피보나치 수열

EX) 0 1 1 2 3 5 8 13 24

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>recursion2</title>
</head>

<body>
    <script>

        function fibonacci(num) {
            if (num < 2) return num;
            else
                return fibonacci(num - 2) + fibonacci(num - 1);
        }
        console.log(fibonacci(0));
        console.log(fibonacci(1));
        console.log(fibonacci(2));
        console.log(fibonacci(3));
        console.log(fibonacci(4));
        console.log(fibonacci(5));
    </script>
</body>

</html>

 

- 2^n승을 구하는 재귀함수

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>recursion2</title>
</head>

<body>
    정수입력 : <input type="text" id="txt">
    <input type="button" value="결과" onclick="main()">
    <script>
        function main(){
            let num = parseInt(document.getElementById("txt").value);
            console.log(powerOfTwo(num));
        }

        //0 이상 정수 n을 입력받아서 2^n을 계산하여 반환하는 재귀함수를 작성해라.
        function powerOfTwo(num){
            if (num != 0)
                return 2 * powerOfTwo(num - 1);
            else
                return 1;
        }

    </script>
</body>

</html>

 

- object(객체) *****

- 속성 추가

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>object</title>
</head>
<body>
    <script>
        // 객체 선언 방법
        let car ={type:"audi", model:"A8", weight:"850kg",color:"white"};
        // console.log(typeof car);
        // let car =new Object();
        console.log(car);

    </script>
</body>
</html>

위와 같이 properties를 확인할 수 있다.

 

        // 객체 선언 방법
        let car ={type:"audi", model:"A8", weight:"850kg",color:"white"};
        // console.log(typeof car);
        // let car =new Object();
        console.log(car);
        document.getElementById("car").innerHTML = car.type;

car.type이 위와 같이 html에 넣어졌다.

 

        let person=new Object();
        person.name="LEE";
        person.gender="male";
        person.age=32;
        console.log(person);

ㄴ 이렇게 해도 객체에 속성이 들어가지만

 

        let person=new Object();
        person["name"]="LEE";
        person["gender"]="male";
        person["age"]=32;
        console.log(person);
        for(let pName in person){
            console.log(pName+":"+person[pName]);
        }

ㄴ 이와 같이 쓰일 수도 있다. []는 배열에서도 쓰이지만 js에서는 객체에서도 쓰인다.

 

- 메서드 추가

        // 함수 이름이 들어가있다.
        let fct=function sleep(){
            console.log("사람은 8시간 잔다.");
        };

 

        // 하지만 함수 이름이 빠진다고 기능이 없어지지는 않는다.
        // 이를 익명함수라고 한다.
        let fct=function(){
            console.log("사람은 8시간 잔다.");
        };
        fct();

ㄴ ES5에서 추가됐다.

 

        // 람다 식으로도 가능하다.
        // 익명 함수 => 화살표 함수
        let fct=()=>{
            console.log("사람은 8시간 잔다.");
        };
        fct();

ㄴ ES6에서 추가됐다.

 

- 구조 분해 할당

        // const age = person.age;
        // const name=person.name;
        // 구조 분해 할당
        const{age,name}=person;
        console.log(age);
        console.log(name);
        console.log("name : "+name+", age : "+age);
        console.log(`name : ${name}, age : ${age}`);

 

        function print(p) {
            console.log(`name : ${p.name}, age : ${p.age}`);
        }
        print(person);

        function print2({
            name,
            age
        }) {
            console.log(`name : ${name}, age : ${age}`);
        }
        print2(person);

ㄴ 출력하는 방식이 두가지가 있다.

'ICIA 수업일지' 카테고리의 다른 글

2021.07.27 수업일지  (0) 2021.07.31
2021.07.26 수업일지  (0) 2021.07.31
2021.07.22 수업일지  (0) 2021.07.24
2021.07.21 수업일지  (0) 2021.07.24
2021.07.20 수업일지  (0) 2021.07.24