Javascript 기초 2

금송·2024년 8월 16일
0

이론

목록 보기
7/17
post-thumbnail

파선아실

파라미터는 선언할 때, 아규먼트는 실행할 때

let a = 1

let b = 2

return a + b

console - console창에 나오는 값

return - 나를 호출한 부분에 반환할 값

추상화

ex) 자동차 운전

운전을 이루는 것들 - 핸들, 엑셀, 브레이크, 기어

핸들, 엑셀, 엔진, 브레이크,기어가 실제로 어떻게 동작하는지 알 필요가 없다.

  • 추상화를 이해하는 것이 왜 중요한가

추상화를 하게되면 코드의 재사용성을 높일 수 있고, 유지보수성도 높일 수 있다.

코딩을 처음 배우게 되면 대부분 추상화를 안한다. 함수로 만들거나 클래스로 만드는 작업을 하지않고 쭉 써서 재사용성도 낮고 유지보수성도 낮은 코드를 작성하게 된다.

// function greet(name) {
//     console.log(`안녕하세요, ${name}님!`);
//     return undefined;
// }
// 위 코드와 동일합니다.
function greet(name) {
    console.log(`안녕하세요, ${name}님!`);
}

greet("licat");
greet("mura");
greet("binky");

구문은 자바스크립트 명령문으로 어떤 작업을 수행 하기 위한 코드 블럭

표현식은 값으로 평가될 수 있는것

일급함수

일급 함수란 함수를 값으로 다룰 수 있다.

괄호가 있으면 실행하는 함수, 변수로도 담을 수 있다

함수의 이름은 변수로 취급 가능

console.log()
alert()
confirm()
parseInt()

let a = console.log
let b = alert
let c = confirm
let d = parseInt

a("hello world")

콜백함수

나중에 널 불러줄게!

함수를 값으로 다루는 기술 중 하나

함수를 다른 함수의 인자(아규먼트)로 넘길 수 있다.

함수를 리턴할 수도 있다.

중급자로 가기 위한 기본적인 지식 / 클로저 공부에 도움이 되는 지식

function licat (f1 ,f2){
    f1(f2("10") + f2("20"))
    return f1;
}
licat (a, d)

함수 선언 방법

// 호이스팅 차이..
// 함수 선언문
function sum(x, y) {
    return x + y;
}

// 함수 표현식
let sumXY = function (x, y) {
    return x + y;
};

console.log(sum(10, 20));
console.log(sumXY(10, 20));

// 화살표 함수
let sum3 = (x, y) => x + y;
// 묵시적으로 return이 들어가있음

// 화살표 함수 다른 형태 - 2
let sum4 = (x, y) => {
    let z = x + y;
    return z;
}
// 화살표 함수 다른 형태 - 3
let sum5 = x => {
    let z = x * 2;
    return z;
}
console.log(sum1(10, 20));
console.log(sum2(10, 20));
console.log(sum3(10, 20));
  • 콜백함수 실습
    // 문제1: 원의 넓이를 구하는 함수
    // 입력: 반지름
    // 함수의 형태: 함수 선언문, 함수 표현식
    
    function circleArea1(x){
        let PI = 3.14;
        return (x*x)*PI
        // Math.PI;
    }
    let circleArea2 = function (x){
        let PI = 3.14
        return (x*x)*PI
    }
    
    // 문제2: 직사각형의 넓이를 구하는 함수
    // 입력: 밑변, 높이
    // 함수의 형태: 함수 선언문, 함수 표현식, 화살표 함수
    function squareArea1 (w,h) {
        return w*h
    }
    let squareArea2 = function (w,h){
        return w*h
    }
    let squareArea3 = (w,h) => w*h;

객체 타입

여러 개의 값을 하나의 단위로 구성한 복합 자료형

key - value로 이루어짐

const로 변수를 잡는다

⇒ obj가 자료형을 향하는건 바뀌지 않고 자료형 내에 내용은 수정

객체 타입 배열

배열은 데이터를 순서대로 저장하는 객체

// 배열
// []로 선언하는걸 먼저 암기
const arr = [10,20,30,40,50];
// 다른 언어와 다르게 index가 넘어가도 error가 발생하지 않음. 그래서 디버깅에 문제가 있었음.
// ex) console.log(arr[6]); // undefined
console.log(arr[0]); // 10
console.log(arr.length); // 5

// 다차원 배열
// , 앞뒤로 공백 허용
// 객체가 유추가 되면 다차원 배열로 적어도 괜찮지만 그렇지 않으면 object 나 map으로 저장.
const arr2 = [
    [1, '홍길동', 70, 80, 90],
    [2, '홍길순', 60, 70, 80],
    [3, '홍길만', 50, 60, 70],
]
console.table(arr2) // 테이블로 정리해서 보여줌
// 홍길동의 평균 점수를 구하세요.
console.log((arr2[0][2] + arr2[0][3] + arr2[0][4])/3) // 80
// 괄호가 없으면 스칼라
// 괄호가 1개 있으면 = 벡터
// 괄호가 2개 있으면 = 메트릭스 (행렬)
// 괄호가 3개 이상 있으면 = 텐서

// google에서 밀고 있는 인공지능 라이브러리인 tensorflow는 괄호가 3개이상 있는 텐서를 이야기한다.
// 인공지능을 아주 단순화 하면 결국 행렬의 연산이다.
// 이미지도, 영상도 결국 행렬이다.

배열의 메서드 1

push - 배열의 요소를 추가하고 싶을 때 쓰는 메소드, 배열의 마지막에 추가됨

pop - 배열의 요소를 삭제하고 싶을 때 쓰는 메소드, 배열의 마지막에 삭제됨

shift - 배열의 요소를 삭제하고 싶을 때 쓰는 메소드, 배열의 처음에 추가됨

unshift - 배열의 요소를 추가하고 싶을 때 쓰는 메소드, 배열의 처음에 삭제됨

// push, pop
const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
// 뒤에서 넣어주고

arr.pop();
console.log(arr); // [1, 2, 3]
// 뒤에서 빼준다

const arr2 = [1, 2, 3];
const last = arr2.pop();
console.log(last); // 3

//shift unshift
const arr3 = [10, 20, 30];
arr3.shift();
console.log(arr3); // [20. 30]

arr3.unshift(40, 50);
console.log(arr3); // [40, 50, 20, 30]

arr3.unshift(100);
console.log(arr3); // [100, 40, 50, 20, 30]

// push 배열의 요소를 추가하고 싶을때 쓰는 메소드, 배열의 마지막에 추가됨
// pop 배열의 요소를 삭제하고 싶을때 쓰는 메소드, 배열의 마지막에 삭제됨
// shift 배열의 요소를 삭제하고 싶을때 쓰는 메소드, 배열의 처음에 삭제됨
// unshift 배열의 요소를 추가하고 싶을때 쓰는 메소드, 배열의 처음에 추가됨

// 깊스넓큐 - 깊이에선 스택, 넓이에선 큐
// 스택 (정처기 문제에도 많이 나옴)
// 스택 - 과자 상자 라고 생각
// 나중에 들어간 과자가 먼저 나오게 된다.
// 스택 > 커런트 >
// push, pop으로 stack 구현하기 -1
const stack = [];
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack); // [1,2,3]
stack.pop();
// stack.shift(); 이렇게 하면 스택이 꺠진다.

// shift, unshift으로 stack 구현하기 -2
const stack2 = [];
stack2.unshift(1);
stack2.unshift(2);
stack2.unshift(3);
console.log(stack2); // [1,2,3]
// stack.pop(); 이렇게 하면 스택이 꺠진다.

// 큐
// 큐 - 원통 놀이기구 라고 생각
// 먼저 들어간 사람이 먼저 나오게 된다.

스택 예시 이미지 (큐는 뚫려있어서 먼저 들어간게 먼저 나옴)

배열의 메서드 2

slice - 배열에서 요소들을 추출하여 새로운 배열로 반환

sort - 배열의 요소를 정리하는데 사용

이때 숫자를 정렬하려할때 문자로 인식해서 이상하게 정렬되는데 이때는 공식을 이용하여 정렬해준다.

* 오름차순
arr4.sort((a, b) => a - b);

* 내림차순
arr4.sort((a, b) => b - a);

// string에서 했었던 것과 같은 방식으로 사용할 수 있음
const arr = [10, 20, 30, 40, 50];
console.log(arr.slice(2)); // 3번째 요소부터 끝까지 추출 [30, 40, 50]
console.log(arr.slice()); // 배열 전체를 추출
console.log(arr.slice(0, 10)); // 배열 전체를 추출

// 알고리즘 문제에서도 잘 나옴 중요!! 정리 잘해두기
// 문제 유형 https://school.programmers.co.kr/learn/courses/30/lessons/120835
// 코인 도장
// 1차원의 점들이 주어졌을 때, 그 중 가장 거리가 짧은 것의 쌍을 출력하는 함수를 작성하시1차원의 점들이 주어졌을 때, 그 중 가장 거리가 짧은 것의 쌍을 출력하는 함수를 작성하시오. (단 점들의 배열은 모두 정렬되어있다고 가정한다.)
// 예를들어 S={1, 3, 4, 8, 13, 17, 20} 이 주어졌다면, 결과값은 (3, 4)가 될 것이다.
// sort
// 배열을 정렬합니다. 기본적으론 오름차순으로 정렬
const arr2 = [20, 10, 50, 40, 30]
arr2.sort();

// 문제 1
// 사전식 정렬
const arr3 = [20, 2, 10, 3, 50, 40, 30];
arr3.sort(); // [10, 2, 20, 3, 30, 40, 50]

// 문제 2
// 브라우저 마다 사용하는 정렬 알고리즘이 다름! (크롬, 파이어폭스, 사파리, 엣지)
// 그나마 이 문제는 많이 해소됨

// 그래서 어떻게 하면 정렬을 순서대로 할수 있나요
// sort 메소드에 함수를 넣어주면 된다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

const arr4 = [20, 2, 10, 3, 50, 40, 30];
// 오름차순
arr4.sort((a, b) => a - b);
// 내림차순
arr4.sort((a, b) => b - a);

// 2. 그래서 오류가 나지 않는 코드는 무엇..
// 보통 이런 코드를 회사 유틸리티 코드로 가지고 있음
// 요즘은 유틸리티코드가 없어도 claude가 워낙 잘 짜줌
jsonData.sort((a, b) => (a[key] > b[key] ? -1 : (a[key] < b[key] ? 1 : 0)));
  • sort 예제
    // 쌍, 거리 등등 은 정렬 문제
    // 1차원의 점들이 주어졌을 때, 그 중 가장 거리가 짧은 것의 쌍을 출력하는 함수를 작성하시오. (단 점들의 배열은 모두 정렬되어있다고 가정한다.)
    //
    // 예를들어 S={1, 3, 4, 8, 13, 17, 20} 이 주어졌다면, 결과값은 (3, 4)가 될 것이다.
    // 쌍을 구하는 것
    
    // const s = [1, 3, 4, 8, 13, 17, 20]
    // const zip = (a, b) => a.map((e, i) => [e, b[i]])
    
    // a = [1, 3, 4, 8, 13, 17, 20]
    // b = [3, 4, 8, 13, 17, 20]
    // 1번째 쌍으로 묶어주기
    
    // a, b가 배열이기 때문에 아래와 같이 할 수 없음
    // zip(s, s.slice(1)).sort((a, b) => b - a)
    
    // const result = zip(s, s.slice(1))
    // result.sort((a, b) => (a[1] - a[0]) - (b[1] - b[0]))
    // result
    
    ///////////////////////////////////////
    
    const s = [1, 3, 4, 8, 13, 17, 20]
    const zip = (a, b) => a.map((e, i) => [e, b[i]])
    const result = zip(s, s.slice(1))
    result.sort((a, b) => (a[1] - a[0]) - (b[1] - b[0]))
    result[0]

배열 메소드 3

forEach - 한땀한땀 실행, 순회를 돌고 싶을 때 사용 but 반복만 하고 새로운 배열을 생성하지 않음

map - forEach와 같지만 차이는 반복하고 새로운 배열을 생성

// forEach
// 한땀한땀 실행, 순회를 돌고 싶을때 사용
const a = [1, 2, 3, 4, 5]
a.forEach((value, index, object) => {
  console.log(value, index, object)
})

//forEach를 통해 해당 값에 제곱값을 출력하는 코드를 작성
const b = [1, 2, 3, 4, 5]
b.forEach(v => {
  console.log(v * v)
})

// 다음 배열에 하트를 추가하는 코드를 작성
const c = ['제주', '서울', '강릉', '부산']
const result = [];
c.forEach(v => {
  result.push(v + '하트')
})
console.log(result)

// map(면접장에서 문제로 자주 나옴)
// forEach 와 map의 차이
// forEach는 반복만 하고 새로운 배열을 생성하지 않음
// map은 반복도 하고 새로운 배열을 생성
const d = [1, 2, 3, 4, 5]
const e = d.map(v => v * v)

const data = [
  {
    "_id": "96286ced-1e1d-4976-B061-9cc7f3f6792d",
    "index": "1",
    "name": "애소희",
    "email": "user-2v0rrn2@simply.biz",
    "phone": "010-8748-1766",
    "country": "레소토",
    "address": "마포대로 14-5",
    "job": "은행출납사무원",
    "age": "38"
  },
  {
    "_id": "e316a6d0-ab67-48da-Ca6f-99a082af41d9",
    "index": "2",
    "name": "부선",
    "email": "user-nnuo0fr@magnis.io",
    "phone": "010-5325-3002",
    "country": "파나마",
    "address": "학동로 28-9",
    "job": "웹디자이너",
    "age": "24"
  },
  {
    "_id": "9f1e9324-7660-4d91-C20c-cb5747578136",
    "index": "3",
    "name": "사도희",
    "email": "user-4y97h5f@neque.org",
    "phone": "010-5355-3285",
    "country": "부탄",
    "address": "성산로 18-4",
    "job": "전자공학기술자",
    "age": "23"
  },
  {
    "_id": "1527e4da-67b4-4d6b-C87e-6967152c42fa",
    "index": "4",
    "name": "왕재윤",
    "email": "user-7pw92n2@Proin.biz",
    "phone": "010-6146-7257",
    "country": "룩셈부르크",
    "address": "남부순환로 2-4",
    "job": "철도 및 지하철기관사",
    "age": "35"
  },
  {
    "_id": "900f16e4-a15d-4a85-A774-816a080edf0b",
    "index": "5",
    "name": "편나희",
    "email": "user-3hokio5@who.biz",
    "phone": "010-2983-6184",
    "country": "리투아니아",
    "address": "논현로 56-8",
    "job": "시각디자이너",
    "age": "28"
  }
]

const result2 = data.map(v => v['age'])

배열 메소드 4

// includes
const arr1 = ['hello', 'world', 'hojun'];
console.log(arr1.includes('world')); // true - 'world'가 배열에 포함됨

const arr2 = ['hello', 'world', 'hojun'];
console.log(arr2.includes('leehojun')); // false - 'leehojun'이 배열에 포함되지 않음

const arr3 = ['hello', 'world', 'hojun'];
console.log(arr3.includes('jun')); // false - 'jun'이 배열에 포함되지 않음

const arr4 = [10, 20, 30, 40];
console.log(arr4.includes(10)); // true - 10이 배열에 포함되어 있음

// join
const arr5 = ['hello', 'world', 'hojun'];
arr5.join(' ') // hello world hojun
arr5.join('-') // hello-world-ahojun

// 유효성 검사 확실하게 할 생각으로 만들어야함
// 번호 입력칸이라고 번호만 입력한다는 생각은 하지 않아야함.
const phone = '010-5044-2903'.split('-')
console.log(phone.join(''))

객체

const d = {
    name : 'hojun',
    age : 27,
    height : 180
};

console.log(d);
console.log(d['name']); // 속성 접근 방식은 이 방식을 권고
console.log(d.name);

delete d.age; // 사용을 많이 하지 않음
console.log(d);

// in 연산자
// in은 key값만 기준으로 함
'name' in d; //true
// 그런데 왜 아래 예제는 false가 나올까
10 in [10, 20, 30, 40, 50]; // fales
// 이 배열 안에 있는 [10]은 key값이 아니라 value라서 그렇다. 대신 인덱스 값을 넣으면 true가 나옴.
0 in [10, 20, 30, 40, 50]; // true

//유사 배열 객체
const arr = {
    0: 10,
    1: 20,
    2: 30,
    3: 40,
    length: 4
}

console.log(arr);
console.log(arr[0]);

//객체의 중첩
const company = {
    name: 'Continental',
    location: {
        city: 'New York',
        country: 'USA'
    },
    employees: {
        manager: 'Winston',
        concierge: 'Charon'
    }
};

console.log(company.location.city); // New York
console.log(company.employees.manager); // Winston
console.log(company['employees']['manager']); // Winston, 하나씩 쳐가며 확인해보기

// 객체의 메소드
const obj = {
    name : 'hojun',
    age : 27,
    height : 180
};

console.log(Object.keys(obj)); // ['name', 'age', 'height']
// obj,keys() 이렇게 되야될 것 같은데 왜 Object.keys(obj) 인가요?
// 이 문제는 클래스 파트에서 다루게 됨
// 만약 obj,keys()가 된다면 arr.keys()도 되어야 한다.
console.log(Object.values(obj))
console.log(Object.entries(obj))
  • 배열과 객체 예제
    // 문제 1번
    // 다음 arr에서 평균을 구해주세요. forEach 메서드를 사용해주세요
    const arr = [10, 20, 30, 40, 50];
    
    // console.log((arr[0] + arr[1] + arr[2] + arr[3] + arr[4])/5)
    let sum = 0
    arr.forEach((v) => {
        sum += v;
    })
    console.log(sum / arr.length)
    
    //let result = 0;
    // arr.forEach(function (value) {
    //     result += value;
    // });
    // console.log(result / arr.length);
    
    // 문제 2번
    // 다음 회전초밥 배열에서 3번째 먹을 수 있는 초밥은 무엇인가요? 차례대로 먹습니다.
    const sushi = ['연어', '참치', '광어', '바다장어', '우럭']
    
    console.log(sushi[2])
    // 이렇게 하면 앞에 '연어'. '참치'가 남아있어서 이렇게 풀면 안됨
    sushi.shift()
    sushi.shift()
    console.log(sushi.shift())
    
    // 문제 3번
    // 다음 객체에서 직원 나이의 평균을 구하세요.
    const employees = [
        {
            name: 'hojun',
            age: 27
        },
        {
            name: 'minji',
            age: 25
        },
        {
            name: 'jihye',
            age: 30
        }
    ];
    
    // let sum = 0;
    // employees.forEach(em => {
    //     sum += em.age;
    // });
    // console.log(sum / employees.length);
    //
    // let sum2 = 0
    // const ages = employees.map(v => v['age'])
    // ages.forEach(v => sum2 += v)
    // console.log(sum2 / employees.length)
    
    // 문제 4번
    // '010 0000 0000'을 '010-0000-0000'으로 바꿔주세요.
    const phone = '010 0000 0000';
    
    console.log(phone.split(' ').join('-'))
    
    // const result2 = phone.split(' ').join('-');
    // console.log(result2);

조건문

let 초록불 = false;

if (초록불) {
    console.log('횡단보도를 건넙니다.')
} else {
    console.log('기다립니다.')
}

if (true) {
    console.log('실행합니다1')
    if(true) {
        console.log('실행합니다2')
    }
}

if (3 < 10) {
    console.log('실행합니다3')
}

const value1 = 'hello'; //true로 판탄
const value2 = ''; // false로 판단
const value3 = null;// false로 판단
const value4 = []; // 주의!! 빈 배열도 true로 판탄

if (value4) {
    console.log('value4는 Truthy한 값입니다.')
}
// 한줄의 경우 중괄호 생략 가능. 권장까진 하지 않음
if(true) console.log('중괄호를 생략했습니다.');

// 논란이 많았던 구조
// 다른 언어
// 'hello' => true
// '' => false
// [10, 20] => true
// [] => false

// 그런데 왜 자바스크립트에선
// 'hello' => true
// '' => false
// [10, 20] => true
// [] => true // 컴퓨터 입장에선 빈 배열을 가지고 있어서 true

// if , else if, else
let score = 91;
let grade;

if (score > 90) {
    grade = 'A';
} else if (score > 80) {
    grade = 'B';
} else if (score > 70) {
    grade = 'C';
} else if (score > 60) {
    grade = 'D';
} else {
    grade = 'F';
}

console.log(`당신의 학점은 ${grade}입니다.`);

// 만약 위 구문이 if문으로만 되어 있다면 무슨 문제가 있는지 확인
// 개별실행되어 아래 grade1는 D가 나옴
let score1 = 91;
let grade1;

if (score1 > 90) {
    grade1 = 'A';
}
if (score1 > 80) {
    grade1 = 'B';
}
if (score1 > 70) {
    grade1 = 'C';
}
if (score1 > 60) {
    grade1 = 'D';
}

// switch문
// break가 없이 실행하면 해당 내용 이후 내용 모두 실행
let fruit = 'apple';
switch (fruit) {
    case 'banana':
        console.log('바나나입니다.');
        break;
    case 'apple':
        console.log('사과입니다.');
        break;
    case 'mango':
        console.log('망고입니다.');
        break;
    default:
        console.log('일치하는 과일이 없습니다.');
}

const attackType = '빔공격'
switch (attackType){
    case '빔공격':
    case '할퀴기공격':
        console.log('10에 데미지를 입혔습니다.')
        break;
    case '방어막공격':
        console.log('5에 데미지를 입혔습니다.')
        break;
}

switch (2) {
    case 1:
        console.log('월요일입니다.');
        break;
    case 2:
        console.log('화요일입니다.');
        break;
    case 3:
        console.log('수요일입니다.');
        break;
    case 4:
        console.log('목요일입니다.');
        break;
    case 5:
        console.log('금요일입니다.');
        break;
    default:
        console.log('주말입니다.');
        break;
}

switch (2) {
    case 1:
        console.log('월요일입니다.');
    case 2:
        console.log('화요일입니다.');
    case 3:
        console.log('수요일입니다.');
    case 4:
        console.log('목요일입니다.');
    case 5:
        console.log('금요일입니다.');
    default:
        console.log('주말입니다.');
}

반복문 for , 간이 테이블 만들기

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>반복문 for</title>
    <style>
        table, tr, th, td {
            border: 1px solid black;
            border-collapse: collapse;
        }
    </style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>번호</th>
                <th>책이름</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
<script>
    // 특정코드를 반복하고 싶을때 사용
    for (let i = 0; i < 10; i++){
        console.log(i)
    }

    const books = ['페스트', '변신', '카프카', '나니아 연대기', '차라투스트라는 이렇게 말했다', '구의 증명']
    let htmlTbody = ''
    for (let i = 0; i < books.length; i++){
        htmlTbody += `<tr>
                          <td>${i + 1}</td>
                          <td>${books[i]}</td>
                      </tr>`
    }
    console.log(htmlTbody)
    document.querySelector('tbody').innerHTML = htmlTbody;
</script>
</body>
</html>
let x = 10;
x = x + 10; // x가 반복되니 줄이고 싶다
x += 10; // x = x + 10; 과 같은 의미
console.log(x)

for (let i = 0; i < 10; i += 3){
    console.log(i)
}

/////////////////////////////////////
// 구구단 출력
for (let i = 2; i <= 9; i++) {
    for (let j = 1; j <= 9; j++) {
        console.log(`${i} x ${j} = ${i * j}`);
    }
}

반복문 while

let x = 10;
while (x < 10) {
    console.log(x); // 이렇게 코드 짜면 안됨, 메모리를 엄청 잡아먹음. 영원히 실행되는 코드
    x++; //증감식이 꼭 있어야한다.
}
// 무한루프
// 메모리를 어마어마하게 많이 잡아 먹음. 그래서 무한루프의 경우 서버가 다운되거나, 브라우저가 다운되는 경우가 있음.

let num = 0;
while (num <= 10) {
    console.log(num);
    if (num === 5) {
        break; // num이 5일 때 반복문을 종료합니다.
    }
    num++;
}

let num2 = 0;
let num3 = 0;
while (num2 <= 10) {
    while (num3 <= 10) {
        console.log(num2, num3);
        if (num3 === 5) {
            break;
        }
        num3++;
    }
    // if (num3 === 5) {
    //         break;
    // }
    num2++;
}

for (let i = 0; i < 20; i++) {
    if (i < 13) {
        continue; // i가 13 미만이면 아래 코드를 건너뜁니다.
    }
    console.log(i + '살은 청소년입니다.');
}

전개구문

전개 구문은 배열이나 객체와 같은 데이터 구조를 확장할 때 사용하는 문법

이를 통해 배열이나 객체를 쉽게 복사하거나, 새로운 배열이나 객체를 생성할 수 있음

전개 식이라고 표현

// 전개구문
Math.max(1,2,3,4,5); // 5
Math.max([1,2,3,4,5]); // NaN

const numbers = [1,2,3,4,5];
Math.max(numbers); // NaN
Math.max(...numbers); // 5

const a = [1, 2, 3];
const b = [4, 5, 6];
const c = [...a, ...b]; // [1, 2, 3, 4, 5, 6]
const d = [a, ...b]; // [[1, 2, 3], 4, 5, 6]

const 과일들 = ['사과', '파인애플', '수박'];
const 과일들2 = 과일들

과일들2[0] = '포도';
console.log(과일들); // ['포도', '파인애플', '수박']

const 과일들3 = [...과일들];
과일들3[0] = '바나나';
console.log(과일들); // ['포도', '파인애플', '수박']

// 컴퓨터 친화적으로 내용을 저장하는 메모리 공간이 다르기에 가르키는 값이 달라 false로 나옴.
const one = ['사과', '파인애플', '수박']
const two = ['사과', '파인애플', '수박']
console.log(one === two); // false

const 위니브1 = { 개리: 1, 빙키: 2 };
const 위니브2 = { 라이캣: 3 };
const 위니브3 = { ...위니브1, ...위니브2 };

console.log(위니브3);

디스트럭처링

const [a, b, c] = [1, 2, 3];

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

// ES6부터 지원하는 문법
// 구조를 해체하는 행위
// let food1, food2, food3;
//
// const categories = { food1: '과일', food2: '채소', food3: '육류' };
//
// food1 = categories.food1;
// food2 = categories.food2;
// food3 = categories.food3;
//
// console.log(food1);
// console.log(food2);
// console.log(food3);

// 디스트럭처링 기본 구조
const { food1, food2, food3 } = { food1: '과일', food2: '채소', food3: '육류' };

console.log(food1);
console.log(food2);
console.log(food3);

this

글로벌 기업에서도 이 코드의 사용을 주의해서 사용하거나 지양하는 경향이 있음

상황에 따라 다르게 동작하고 있어서 외워야 하는 예외 케이스가 많음

‘나 자신’이라고 생각 해주면, 초급자 분들에게는 충분하다고 생각 하지만 +a로 조금 더 알아두는게 좋을 듯 함

다양한 예외 케이스가 있어 정의 내리기 어려움

console.log(this) // window
this.alert('hello') // = window.alert('hello')

function f() {
    console.log(this) // window
}
f();

const obj = {
    name: 'licat',
    f : function () {
        console.log(this);
    }
}

obj.f(); // obj , 오브젝트 자기 자신

function Person(name) {
    //여기서 this는 person1
    this.name = name;
    console.log(this);
    // return this 가 생략되어 있음
}

const person1 = new Person('licat'); // Person { name: "licat" }
const person2 = new Person('mura');// Person { name: "mura" }
profile
goldsong

0개의 댓글