본문 바로가기
ICIA 수업일지

2021.07.26 수업일지

by 주성씨 2021. 7. 31.

- Java Script review

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

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

<body>
    <h3 id="car"></h3>
    <h3 id="person"></h3>
    <script>
        // 객체 선언 방법
        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;

        // 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;
        // []는 배열에서도 쓰지만 JS에서는 객체에서도 쓰인다.
        // person.name은 변수가 안되지만 person["name"]은 변수로 쓰일 수 있다.
        console.log(person);

        // person 속성을 방아서 pName에 하나씩 넘긴다.
        // 1) person.pName은 못씀 속성이 아니기때문
        for (let pName in person) {
            console.log(pName + ":" + person[pName]); // 1)
        }

        // 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({ // ES6 구조분해 할당
            name,
            age
        }) {
            console.log(`name : ${name}, age : ${age}`);
        }
        print2(person);

        // 메서드 추가
        // person.sleep = function sss() {
        //     console.log("사람은 8시간 잔다.");
        // };
        // person.sleep();


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

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

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

        function test(fct) {
            fct(20);
        }

        test((a) => console.log("사람은 " + a + "시간 잔다."));
    </script>
</body>

</html>

 

- 메서드 추가

        // 1단계 익명함수
        let fct=function(){
            console.log("사람은 8시간 잔다.");
        };
        fct();

 

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

 

11_object02

        // 1) 오브젝트 생성
        let account = {};
        // 2) 속성 생성
        account["balance"]=0; //잔고
        // 3) 예금 메서드
        account["deposit"]=function(amount){
            // account.balance+=amount;
            this.balance+=amount;
        }
        
        // // this. 사용시 => 함수 사용 금지
        // account["deposit"]=(amount)=>{
        //     console.log("this1",this); // window 객체
        //     this.balance+=amount;
        // }
        // 4) 출금 메서드
        account["wihdraw"]=function(amount){
            if(amount <= this.balance){
            this.balance-=amount;
            }else{
                console.log("잔액이 부족합니다.")
            }
        }
        // 5) 오브젝트 객체 사용
        // ※ JS toString 메서드 재정의
        account.toString = function(){
            return "balance : "+this.balance;
        }

        account.balance=500;
        account.deposit(1000);
        account.wihdraw(200);
        // toString 재정의를 통해서 출력을 바꿀 수 있다.
        console.log(account.toString());
        console.log(account);

        account.wihdraw(700);
        console.log(account.toString());

 

12_object03

    <script>
        // 함수(생성자)로 오브젝트 생성
        function Account(amount) {
            this.balance = amount;
            this.deposit = deposit;
            this.withdraw = withdraw;
            this.toString = toString;
        }

        function deposit(amount) {
            this.balance += amount;
        }

        function withdraw(amount) {
            if (amount <= this.balance) {
                this.balance -= amount;
            } else {
                console.log("잔액이 부족합니다.")
            }
        }

        function toString() {
            return "balance : " + this.balance;
        }

        let account = new Account(500);
        account.deposit(1000);
        console.log(account.toString());

    </script>

 

+ 생성자 밖에서 추가할 때

        function Account(amount) {
            this.balance = amount;
            // this.deposit = deposit;
            this.withdraw = withdraw;
            this.toString = toString;
        }

        // 생성자 밖에서 추가할 때
        Account.prototype.deposit = function(amount){
            this.balance += amount;
        }

        // function deposit(amount) {
        //     this.balance += amount;
        // }

 

+ 새로운 메서드 추가

        account.test = () => console.log("test method");
        account.test();

 

13_object04 ***

- ES6에서는 class 지원

        //ES6에서는 class 지원
        class Account {

            // 생성자 만들기
            constructor(money) { //Account 에러
                this.balance = money;
                //this.deposit = deposit;
                //this.withdraw = withdraw;
                //this.toString = toString;
            } //생성자 End

            //메소드 정의
            deposit(amount) { // 입금
                this.balance += amount;
            }

            withdraw(amount) { // 출금
                if (amount <= this.balance) {
                    this.balance -= amount;
                }
                if (amount > this.balance) {
                    console.log("잔액이 부족 합니다.");
                }
            }

            //자바스크립트의 toString메소드 재정의
            toString() { // 잔액 확인
                return "balance: " + this.balance;
            }

        } //class End

 

        //오브젝트 사용
        let account = new Account(500);
        account.deposit(1000);
        //Object(부모)의 toString()호출
        console.log(account.toString());
        console.log(account); //객체 정보
        account.withdraw(700);
        console.log(account.toString());
        account.withdraw(1000);
        console.log(account.toString());

 

14_this

    <input type="button" id="bt1" value="button1" onclick="fct(this)">
    <input type="button" id="bt2" value="button2" onclick="fct(this)">

    <script>
        function fct(obj) {
            console.log("obj = ",obj); // 현재 이벤트 객체
            if(obj.value=="button1"){
                document.getElementById("bt2").value = "button2";
                obj.value="버튼1 입니다.";
            }
            if(obj.value=="button2"){
                document.getElementById("bt1").value = "button1";
                obj.value="버튼2 입니다.";
            }
        }
    </script>

 

 

15_array

        // 1) 배열 선언의 두가지 방법
        let arrayNum =[];
        let arrayString = new Array();
        // 2) 배열에 값 넣기
        arrayNum = [1,2,3,4];
        arrayString = ["a","b","c","d"];
        // 3) 배열에 값 추가하기
        // arrayNum[4]=5;
        // arrayNum[arrayNum.length]=5;
        arrayNum.push(5); // 배열의 마지막 요소에 값 추가
        arrayNum.push(6);
        arrayString.push("e");
        console.log(arrayNum);
        console.log(arrayString);
        // 4) 배열 여부 확인하는 법
        console.log(Array.isArray(arrayNum));
        console.log(Array.isArray(arrayString));

 

16_arrayAddDel

  • 배열 rear에서 입력하는 것을 push 출력하는 것을 pop이라고 한다.
  • 베열 front에서 입력?하는 것을 unshift 출력?하는 것을 shift라고 한다.

https://stackoverflow.com/questions/8073673/how-can-i-add-new-array-elements-at-the-beginning-of-an-array-in-javascript

 

How can I add new array elements at the beginning of an array in Javascript?

I have a need to add or prepend elements at the beginning of an array. For example, if my array looks like below: [23, 45, 12, 67] And the response from my AJAX call is 34, I want the updated ar...

stackoverflow.com

 

<body>
    <!-- 중요1 -->
    <button onclick="arrPush()">push</button>
    <!-- 중요2 -->
    <button onclick="arrPop()">pop</button>
    <button onclick="arrUnshift()">unshift</button>
    <button onclick="arrShift()">shift</button>

    <script>
        // 배열 선언 3가지
        let arrNum = [];
        let i;
        // let arrNum = Array(5);
        // let arrNum = new Array(5);

        // 반복문으로 배열값 채워넣기
        for(i=0;i<5;i++){
            arrNum[i] =i+1;
        }

        // 배열에 특정 값만을 채워넣기
        // let arrNum=Array(5);
        // arrNum.fill(0);

        console.log(arrNum); // 배열 객체 확인
        function arrPush(){
            arrNum.push(i+1);
            i++;
            console.log(arrNum);
        }
       
        function arrPop(){
            arrNum.pop();
            console.log(arrNum);
        }

        // 배열의 앞에 값을 추가
        function arrUnshift(){
            arrNum.unshift(i+1);
            i++;
            console.log(arrNum);
        }

        // 배열의 앞에 값을 삭제
        function arrShift(){
            arrNum.shift();
            console.log(arrNum);
        }

    </script>
</body>

 

17_arrayMethod ***

    <button onclick="joinEx()">Join</button>
    <br />
    <button onclick="delEx()">Delete</button>
    <button onclick="spliceDel()">spliceDel</button>
    <button onclick="spliceAdd()">spliceAdd</button>
    <br />

    <button onclick="sortEx()">정렬</button>
    <button onclick="reverseEx()">역정렬</button>
    <button onclick="numberSort()">
        숫자정렬
    </button>
    <br />
    <button onclick="concatEx()">
        배열 병합
    </button>
    <button onclick="sliceEx()">
        범위 자르기
    </button>

 

1. join ; 끼워넣기

        let arr = ["마", "가", "다", "바", "나", "라"];

        // Join ; 배열 사이에 특정 객체를 넣는다.
        function joinEx() {
            let arr = ["a", "b", "c", "d", "e"];
            console.log(arr.join("$"));
        }

 

2. delete ; 삭제하기

        let arr = ["마", "가", "다", "바", "나", "라"];

        // delete ; 특정 배열을 삭제 한다.
        function delEx() {
            delete arr[2];
            console.log(arr);
            arr[2] = "new";
            console.log(arr);
        }

 

3. sort ; 정렬

        let arr = ["마", "가", "다", "바", "나", "라"];

        // sort ; 정렬
        function sortEx() {
            arr.sort();
            console.log(arr);
        }

 

4. reverse ; 역순

        let arr = ["마", "가", "다", "바", "나", "라"];

        // 역정렬
        function reverseEx() {
            arr.reverse();
            console.log(arr);
            console.log(arr[0]);
        }

 

5. numbers.sort ; 숫자정렬

        // 숫자 정렬(number Sort)
        let numbers = [8, 12, 13, 41, 15, 23];

        function numberSort() {
            numbers.sort(function (a, b) {
                return a - b;
            });
            console.log(numbers);
        }

 

6. concat ; 배열 병합(통합)

        // 배열 병합 ; 연결
        function concatEx() {
            let arr1 = [1, 2, 3, 4, 5];
            let arr2 = ['a', 'b', 'c', 'd'];
            let newArr = arr1.concat(arr2);
            console.log(arr1);
            console.log(arr2);
            console.log(newArr);
        }

 

7. split ;

        // 구분자로 잘라서 배열에 넣기
        let text = "구분자로 잘라서 배열에 넣기";
        let words = text.split(" "); // 공백으로 잘라서 배열에 저장
        for (let idx in words) {
            console.log("[" + idx + "] : " + words[idx]);
            console.log(`[${idx}] : ${words[idx]}`)
        }

 

8.  slice ; 필요한 배열 범위 자르기

        function sliceEx() {
            var sarry = [0, 1, 2, 3, 4, 5];
            //1번 인덱스 부터 보여주고, 3번 인덱스 부터 잘라냄
            var newArr = sarry.slice(1, 3);
            console.log(newArr);
            //1번 인덱스 부터 끝까지...
            newArr = sarry.slice(1);
            console.log(newArr);
        }

 

9. splice ;

        let arr = ["마", "가", "다", "바", "나", "라"];
        //splice 요소 삭제
        function spliceDel(){
            //x번 인덱스 부터, n개 삭제
            arr.splice(2,2);
            console.log(arr);            
        }
        
        //splice 요소 추가
        function spliceAdd(){
            //x번 인덱스, 삭제할 요소 수,추가할 값
			//arr.splice(2,2,"C","D");//2개 삭제 후 2개 대체
            arr.splice(2,0,"C","D"); //0개 삭제 후 2개 추가
            console.log(arr);
        }

 

18_arrayTest

<body>
    <!-- 정수입력 -->
    <input type="text" id="in" />
    <input type="button" value="insert" onclick="input()" />
    <input type="button" value="Max" onclick="getMaxMin(this)" />
    <input type="button" value="Min" onclick="getMaxMin(this)" />

    <script>
        let arr = [];

        function input() {
            //arr 배열에 정수를 저장
            arr.push(parseInt(document.getElementById("in").value));
            console.log(arr);
            document.getElementById("in").focus();
            document.getElementById("in").value = "";
        }

        function getMaxMin(obj) {
            // 최대값 또는 최소값 구해서 콘솔에 출력
            // for, if문으로 구하거나 정렬로 구하거나 편한대로
            let max, min;
            max = min = arr[0];
            if (obj.value == "Max") {
                for (let val of arr) {
                    if (max < val) {
                        max = val;
                    }
                }
                console.log("최대값 : "+max);
            } else {
                for (let val of arr) {
                    if (min > val) {
                        min = val;
                    }
                }
                console.log("최소값 : "+min);
            }
        }
    </script>
</body>

 

            // 정렬문으로 해보기
            if (obj.value == "Max") {
                arr.sort((a,b)=>a-b);
                console.log(arr[arr.length - 1]);
            } else {
                arr.sort((a,b)=>a-b);
                console.log(arr[0]);
            }

 

- shallow(얕은) copy <--> deep(깊은) copy

ㄴ 원본은 그대로 두고 복사본을 만들어 데이터를 수정하고 싶을때 deep copy를 사용하고 그게 아니면 shallow copy를 사용한다. 

 

<body>
    <script>
        function shallowCopy() {
            let num = [];

            for (let i = 0; i < 10; i++) {
                num[i] = i + 1;
            }
            console.log("num : " + num);

            let copyNum = num; //얕은 복사
            console.log("copyNum : " + copyNum);

            //nums[0] 값이 변화 했을 때 copyNum[0] 값이 어떻게 변할까?
            num[0] = 50;
            //두 개의 배열 관계는 복사라기 보다는 링크 되었다고 보는것이 옳다.
            console.log("num : " + num);
            console.log("copyNum : " + copyNum);
        }
        shallowCopy();
        //Deep Copy
        let nums = [];
        let copy = [];
        for (let i = 0; i < 10; i++) {
            nums[i] = i + 1;
        }
        copyArr(nums, copy); //깊은 복사 함수

        function copyArr(source, target) {
            for (let i = 0; i < source.length; i++) {
                target[i] = source[i];
            } //for in으로 변경할 것.
            target[0] = 99;
            console.log(target);
            console.log(source);

        }
    </script>
</body>

 

- foreach ; 특정 배열안에 값을 하나씩 빼오는 역할을 한다. 기본적으로 실행 함수에는 각각의 아이템과, 인덱스 정보가 들어온다.

    <script>
        let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        arr.forEach(square); // callbackfn ***

        function square(num, idx, arr) { // square(오소값, 인덱스, 배열참조값)
            console.log(num, num * num);
            console.log(idx);
            console.log(arr);
        }
    </script>

 

        //  익명함수로 이와 같이 간단하게도 가능하다.
        arr.forEach((num)=>console.log(num, num*num));

 

- every

        // every ; 배열 전체를 판단하는 메서드
        let nums = [2,4,6,8,10];
        let even = nums.every((num)=>num%2==0);

        // function isEven(num){ // isEven(요소값, 인덱스, 배열참조값)
        //     return num%2 ==0;
        // }

        if(even){
            console.log("모든 숫자가 짝수 입니다.")
        } else{
            console.log("모든 숫자가 짝수가 아닙니다.")
        }

 

- Console

  • Console은 변수의 값을 찍어주는 역할을 한다.
  • 콘솔안에는 다양한 값들을 찍을 수 있다.
  • 또한 로그에는 각 레벨이 있다.
<body>
    <script>
        let str = "문자열 입니다.";
        let obj = {
            "name": "cha"
        }; //{key:value}; Object객체
        let arr = [1, 2, 3, 4, 5]; //Array객체
        console.log(obj.name);
        console.log(obj["name"]);
        for (let pName in obj)
            console.log(obj[pName]);
        
        //어느 로그나 그렇듯이 로그에는 각 레벨이 있다.
        //warn, error는 출력코드를 위치를 알려준다.
        console.log(arr); //Log 정보
        console.dir(arr);
        console.info(arr); //Info 정보 
        console.warn(arr); //Warn 정보
        console.error(arr); //Error정보

        //또한 자바스크립트 로그에서는 어떠한 자료 구조도 표현이 된다.
        console.log(str);
        console.log(obj);
        console.log(arr);
        //다만 아래와 같이 문자열+오브젝트 는 정상적으로 내부 표시가 되지 않는다.
        console.log("object : " + obj);
        //이럴 경우 다음과 같이 표기 할 수 있다.
        console.log("object", obj);
    </script>
</body>

 

- Java Script_DOM (Document Object Model)

웹 표준 디자인

Event - 특정 액션에 일어나는 기능

<body>
    <input type="button" onclick="alert('Hello')" value="click">
    <a href="javascript:fct()">링크</a>
    <script>
        function fct(){
            console.log('hello');
            alert("네이버 이동");
            location.href="http://www.naver.com"
        }
    </script>
</body>

 

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

2021.07.28 수업일지  (0) 2021.07.31
2021.07.27 수업일지  (0) 2021.07.31
2021.07.23 수업일지  (0) 2021.07.24
2021.07.22 수업일지  (0) 2021.07.24
2021.07.21 수업일지  (0) 2021.07.24