티스토리 뷰

//변수
let age = 25; //정수

let tall = 175.9; // 실수

let inf = Infinity; // 무한대

let minusInf = -Infinity; // 음의 무한대

let nan = NaN; // 수학적 연산 실패

console.log(age + tall);
console.log(age * tall);

백틱 & 템플릿리터럴
let name = "rdrd";
let name2 = "자몽";
let name3 = `rdrd ${name2}`; //백틱 & 템플릿리터럴
console.log(name3);

let isSwitchOff = false;

let a;
console.log(a); // undefined
let b = null;
console.log(b); // null

// 변수에 아무것도 할당하지 않았을 때 자동으로 undefined라는 값을 할당 받음
let variable;
console.log(variable); // undefined

숫자 + 문자
값은 유지하며 자료형 변경하는 형변환
let numberA = 12;
let numberB = 2;
console.log(numberA * numberB); // 24

let numberC = 12;
let numberD = "2";
console.log(numberC * numberD); // 24

let numberA = 12;
let numberB = "2";

console.log(numberA + numberB); // 122

console.log(numberA + parseInt(numberB)); // 14

관계연산자
let a = 1;
let b = 2;

console.log(a + b);
console.log(a * b);
console.log(a - b);
console.log(a / b);
console.log(a % b);

형변환
let a = "1";
let b = "2";
console.log(a + b); // 12
b = 2;
console.log(a + b); // 12

let a = 5;
a += 10; // a = a + 10;
console.log(a);

let a = 10;
console.log(a++); // 10
console.log(a);

논리연산자
console.log(!true); // false
console.log(!false); // true

console.log(true && true); // true AND true
console.log(true || false); // true OR true

비교연산자
let compareA = 1 == "1"; // 값만 비교
console.log(compareA); // true

let compareB = 1 === "1"; // 타입도 비교
console.log(compareB); // false

compareA = 1 != "1";
console.log(compareA); // false
compareA = 1 !== "1";
console.log(compareA); // true

대소비교
let compareA = 2 <= 2;
console.log(compareA);

typeof
let compareA = 1;
compareA = "1";

console.log(typeof compareA); // string

null변환 연산자
let a;
a = a ?? 10;
console.log(a); // 10

조건문
let a = 5;

if (a >= 7) {
  console.log("7 이상입니다.");
} else if (a >= 5) {
  console.log("5 이상입니다.");
} else {
  console.log("5 미만입니다.");
}

let country = "ko";

if (country === "ko") {
  console.log("한국");
} else if (country === "cn") {
  console.log("중국");
} else if (country === "jp") {
  console.log("일본");
} else {
  console.log("미 분류");
}

chaning 조건이 많을 때? => switch
let country = "ko";

switch (country) {
  case "ko":
    console.log("한국");
    break;
  case "cn":
    console.log("중국");
    break;
  case "jp":
    console.log("일본");
    break;
  case "uk":
    console.log("영국");
    break;
  default:
    console.log("미 분류");
    break;
}

함수
let width1 = 10;
let height1 = 20;

let area1 = width1 * height1;
console.log(area1);

let width2 = 10;
let height2 = 20;

let area2 = width2 * height2;
console.log(area2);

함수로
function getArea() { //2번!!
  let width = 10;
  let height = 20;

  let area = width * height;
  console.log(area);
} // 함수 선언식, 함수 선언 방식의 함수 생성

getArea(); //1번!!
console.log("함수 실행 완료"); //3번!!

각기다른사각형 면적 구하기
function getArea(width, height) {
  let area = width * height;
  return area;
} // 함수 선언식, 함수 선언 방식의 함수 생성

let area1 = getArea(100, 200);

함수 표현식
let hello = function () {
  return "안녕하세요 여러분";
}; // 함수 표현식

const helloText = hello();
console.log(helloText);

함수 표현식과 선언식의 차이
console.log(helloB()); //호이스팅

let helloA = function () {
  return "안녕하세요 여러분 helloA";
}; // 함수 표현식

console.log(helloA()); //호이스팅XXX

function helloB() {
  return "안녕하세요 여러분 helloB";
} // 함수 선언식

화살표 함수
let helloA = () => "안녕하세요 여러분";
console.log(helloA());

콜백함수
function checkMood(mood) {
  if (mood === "good") {
    //기분 좋을 때 하는 동작
    sing();
  } else {
    //기분 안 좋을 때 하는 동작
    cry();
  }
}

function cry() {
  console.log("ACTION :: CRY");
}

function sing() {
  console.log("ACTION :: SING");
}

function dance() {
  console.log("ACTION :: DANCE");
}

checkMood("sad");

콜백으로 변환
function checkMood(mood, goodCallback, badCallback) {
  if (mood === "good") {
    //기분 좋을 때 하는 동작
    goodCallback();
  } else {
    //기분 안 좋을 때 하는 동작
    badCallback();
  }
}

function cry() {
  console.log("ACTION :: CRY");
}

function sing() {
  console.log("ACTION :: SING");
}

function dance() {
  console.log("ACTION :: DANCE");
}

checkMood("sad", sing, cry);

객체
객체 생성자
let person = new Object();
객체 리터럴 방식
let person = {
  key: "value", //프로퍼티 (객체 프로퍼티)
  key1: 123,
  key2: true,
  key3: undefined,
  key4: [1, 2],
  key5: function () {}
};
console.log(person);
console.log(person.key1);
console.log(person["key1"]);
console.log(person.key2);
console.log(person["key2"]);
console.log(person.key1_1); //없는 property에 접근시 undefined

언제 괄호표기법으로 property를 가져올까?
let person = {
  name: "짜몽",
  age: 20
}; //객체 리터럴 방식

console.log(getPropertyValue("name"));

function getPropertyValue(key) {
  return person[key];
}

객체 생성 이후 property 추가, 삭제
let person = {
  name: "자몽",
  age: 20
};

person.location = "한국";
person["gender"] = "여성";

person.name = "자몽A";
person["age"] = 40;
console.log(person);

property 삭제 - delete 메모리에 그대로있음
let person = {
  name: "자몽",
  age: 20
};

delete person.name;
console.log(person);

property 삭제 - 메모리에서도 지움
const person = {
  name: "자몽",
  age: 20
};

person.name = null;
console.log(person);

const person = {
  name: "자몽",
  age: 25,
  say: function () {
    console.log("안녕");
  } //메서드 -> 방법
};

person.say(); //person["say"]();

이름도바뀌게 백틱 템플릿리터럴
const person = {
  name: "바나나",
  age: 25,
  say: function () {
    console.log(`안녕 나는 ${this.name}`);
  } //메서드 -> 방법
};

console.log(`name : ${"name" in person}`);
console.log(`age : ${"age" in person}`);
console.log(`gender : ${"gender" in person}`);

배열
생성자 이용 방법
let arr1 = new Array();
//배열 리터럴
let arr = [];

console.log(arr); //[]

arr = [1, 2, 3, 4];
console.log(arr);

//자료형이 아무거나 들어와도 상관없다.
arr = [1, "2", true, null, undefined, {}, [], function () {}];
console.log(arr);

숫자 배열 다뤄보기
let arr = [1, 2, 3, 4, 5];
console.log(arr);

//배열 요소 각각에 접근
//배열에는 키값이 없음, 위치 인덱스가 존재함.
//인덱스를 통해 각각의 값에 접근 가능
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
console.log(arr[3]);
console.log(arr[4]);

//배열에 요소 추가
arr.push({ key: "value" });
console.log(arr);
console.log(arr[5]);

배열의 길이 확인
let arr = [1, 2, 3, 4, 5];
console.log(arr.length); //5

반복문
for (let i = 1; i <= 100; i++) {
  // 반복 수행할 명령
  console.log("renee");
}

배열 순회
const arr = ["a", "b", "c"];
for (let i = 0; i < arr.length; i++) {
  // 반복 수행할 명령
  console.log(arr[i]);
}

객체 순회
let person = {
  name: "nana",
  age: 26,
  tall: 165
};

const personKeys = Object.keys(person);

for (let i = 0; i < personKeys.length; i++) {
  const curKey = personKeys[i];
  const curValue = person[curKey];

  console.log(`${curKey} : ${curValue}`);
}

객체순회 배열값만 가져오기
let person = {
  name: "nana",
  age: 26,
  tall: 165
};

const personValues = Object.values(person);

for (let i = 0; i < personValues.length; i++) {
  console.log(personValues[i]);
}

배열 내장함수

const arr = [1, 2, 3, 4, 5];

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

arr.forEach((elm) => console.log(elm));

arr.forEach(function (elm) {
  console.log(elm);
});

arr.forEach(function (elm) {
  console.log(elm * 2);
});

배열 모든 요소*2 해서 새로운 배열 생성
const arr = [1, 2, 3, 4, 5];
const newArr = [];

arr.forEach(function (elm) {
  newArr.push(elm * 2);
});

console.log(newArr);

arr.forEach((elm) => newArr.push(elm * 3));

map사용
const arr = [1, 2, 3, 4];
const newArr = arr.map((elm) => {
  return elm * 2;
});

console.log(newArr);

값이 배열에 존재하는지 안하는지!
inclues & indexOf
const arr = [1, 2, 3, 4, 5];

let number = 3;

arr.forEach((elm) => {
  if (elm === number) {
    console.log(true);
  }
});

console.log(arr.includes(number));
console.log(arr.indexOf(number));

복잡한 객체들을 포함한 배열 이라면?
const arr = [
  { color: "red" },
  { color: "black" },
  { color: "blue" },
  { color: "green" }
];

let number = 3;

console.log(
  arr.findIndex((elm) => {
    return elm.color === "red";
  })
);

console.log(arr.findIndex((elm) => elm.color === "red"));

우리가 찾고자 하는 값에 접근하려면?
굳이 findIndex -----> find!!
const arr = [
  { color: "red" },
  { color: "black" },
  { color: "blue" },
  { color: "green" }
];

let number = 3;

const idx = arr.findIndex((elm) => {
  return elm.color === "red";
});

console.log(
  arr.findIndex((elm) => {
    return elm.color === "red";
  })
);

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

우리가 찾고자 하는 값에 접근하려면?

//find
const arr = [
  { color: "red" },
  { color: "black" },
  { color: "blue" },
  { color: "green" }
];

let number = 3;

const element = arr.find((elm) => {
  return elm.color === "red";
});

console.log(element);

배열을 필터링
find
const arr = [
  { number: 1, color: "red" },
  { number: 2, color: "black" },
  { number: 3, color: "blue" },
  { number: 4, color: "green" },
  { number: 5, color: "blue" }
];

Truthy & falsy
let a = "";
if (a) {
  console.log("TRUE");
} else {
  console.log("FALSE");
}

함수 제작

const getName = (person) => {
  if (person === undefined || person === null) {
    return "객체가 아닙니다";
  }
  return person.name;
};

// let person = undefined;
// let person = null;
let person = { name: "zzamong" };
const name = getName(person);

console.log(name);

//falsy값 사용하기
if (!person) {
    return "객체가 아닙니다";
  }

3항연산자
let a = -3;
a >= 0 ? console.log("양수") : console.log("음수");

a = [];
if (a.length === 0) {
  console.log("빈 배열");
} else {
  console.log("안 빈 배열");
}

a.length === 0 ? console.log("빈 배열") : console.log("안 빈 배열");

//3항연산자 - 값을 참일때와 거짓일 때를 구분해서 반환해보자
const arrayStatus = a.length === 0 ? "빈 배열" : "안 빈 배열";
console.log(arrayStatus);

//3항연산자 - Truthy falsy 구분하기
let a;

let result = a ? true : false;
console.log(result);

a = [];
result = a ? true : false;
console.log(result);

3항연산자 - 중첩 - 학점 계산 프로그램
90점 이상 A+
50점 이상 B+
둘다 아니면 F
let score = 100;
score > 90
  ? console.log("A+")
  : score >= 50
  ? console.log("B+")
  : console.log("F");

if (score >= 90) {
  console.log("A+");
} else if (score >= 50) {
  console.log("B+");
} else {
  console.log("F");
}

//단락 회로 평가
const getName = (person) => {
  const name = person && person.name; // zzamong
  return name || "객체가 아닙니다";
};

// let person = { name: "zzamong" };
let person = null;
const name = getName(person);
console.log(name);

//주어진 문자열이 한식인지 확인하는 함수
function isKoreanFood(food) {
  if (["불고기", "비빔밥", "떡볶이"].includes(food)) {
    return true;
  }
  return false;
}

const food1 = isKoreanFood("불고기");
const food2 = isKoreanFood("파스타");
console.log(food1);
console.log(food2);

주어진 값에 따라서 각각 다른 결과물을 반환하는 함수
const getMeal = (mealType) => {
  if (mealType === "한식") return "불고기";
  if (mealType === "양식") return "파스타";
  if (mealType === "한식") return "멘보샤";
  if (mealType === "일식") return "초밥";
  return "굶기";
};

console.log(getMeal("한식"));
console.log(getMeal("양식"));
console.log(getMeal());

세상에 존재하는 모든 국가 다 포함하려면... 헬
=>객체의 property에 접근하는 괄호표기법으로 혁신적으로 접근

const meal = {
  한식: "불고기",
  중식: "멘보샤",
  일식: "초밥",
  양식: "스테이크",
  인도식: "카레"
};
const getMeal = (mealType) => {
  return meal[mealType] || "굶기";
};

console.log(getMeal("중식"));
console.log(getMeal());

비 구조화 할당
let arr = ["one", "two", "three"];

let one = arr[0];
let two = arr[1];
let three = arr[2];

console.log(one, two, three);


let arr = ["one", "two", "three"];
let [one, two, three] = arr;
console.log(one, two, three);


let [one, two, three] = ["one", "two", "three"];
console.log(one, two, three);


let [one, two, three, four = "four"] = ["one", "two", "three"];
console.log(one, two, three, four);

swap
let a = 10;
let b = 20;
[a, b] = [b, a];
console.log(a, b);

객체의 비 구조화 할당
let object = {
  one: "one",
  two: "two",
  three: "three"
};

let one = object["one"];
let two = object["two"];
let three = object["three"];

console.log(one, two, three);



키 값을 기준으로 할당한다.
let object = {
  one: "one",
  two: "two",
  three: "three"
};
let { one, two, three } = object;
console.log(one, two, three);

변수명 강제 극복
let object = {
  one: "one",
  two: "two",
  three: "three",
  name: "자몽"
};
let { name: myName, one: oneOne, two, three, abc = "four" } = object;
console.log(oneOne, two, three, myName, abc);

spread
객체스프레드
const cookie = {
  base: "cookie",
  madeIn: "korea"
};

const chocochipCookie = {
  ...cookie,
  toping: "chocochip"
};

const blueberryCookie = {
  ...cookie,
  toping: "blueberry"
};

const strawberryCookie = {
  ...cookie,
  toping: "strawberry"
};

console.log(chocochipCookie);
console.log(blueberryCookie);
console.log(strawberryCookie);

배열스프레드

const noTopingCookies = ["촉촉한쿠키", "안촉촉한쿠키"];
const topingCookies = ["바나나쿠키", "블루베리쿠키", "딸기쿠키", "초코칩쿠키"];

const allCookies = [...noTopingCookies, "함정쿠키", ...topingCookies];
console.log(allCookies);

동기 => 비동기
function taskA() {
  setTimeout(() => {
    console.log("A TASK END");
  }, 2000); //타이머만들수 있는 내장 비동기 함수, 2초
}

taskA();
console.log("코드 끝");


function taskA(a, b, cb) {
  setTimeout(() => {
    const res = a + b;
    cb(res);
  }, 3000); //타이머만들수 있는 내장 비동기 함수, 2초
}

taskA(3, 4, (res) => {
  console.log("A TASK RESULT : ", res);
});
console.log("코드 끝");


function taskA(a, b, cb) {
  setTimeout(() => {
    const res = a + b;
    cb(res);
  }, 3000); //타이머만들수 있는 내장 비동기 함수, 2초
}

function taskB(a, cb) {
  setTimeout(() => {
    const res = a * 2;
    cb(res);
  }, 1000);
}

function taskC(a, cb) {
  setTimeout(() => {
    const res = a * -1;
    cb(res);
  }, 2000);
}

taskA(3, 4, (res) => {
  console.log("A TASK RESULT : ", res);
});

taskB(7, (res) => {
  console.log("B TASK RESULT : ", res);
});

taskC(14, (res) => {
  console.log("C TASK RESULT : ", res);
});
console.log("코드 끝");






function taskA(a, b, cb) {
  setTimeout(() => {
    const res = a + b;
    cb(res);
  }, 3000); //타이머만들수 있는 내장 비동기 함수, 2초
}

function taskB(a, cb) {
  setTimeout(() => {
    const res = a * 2;
    cb(res);
  }, 1000);
}

function taskC(a, cb) {
  setTimeout(() => {
    const res = a * -1;
    cb(res);
  }, 2000);
}

taskA(4, 5, (a_res) => {
  console.log("A RESULT : ", a_res);
  taskB(a_res, (b_res) => {
    console.log("B RESULT : ", b_res);
    taskC(b_res, (c_res) => {
      console.log("C_RESULT : ", c_res);
    });
  });
});
console.log("코드 끝");


promise

2초뒤에 전달받은 값이 양수인지 음수인지 체크하는 비동기 함수
콜백을 이용한 비동기함수
function isPositive(number, resolve, reject) {
  setTimeout(() => {
    if (typeof number === "number") {
      //성공 -> resolve
      resolve(number >= 0 ? "양수" : "음수");
    } else {
      //실패 -> reject
      reject("주어진 값이 숫자형 값이 아닙니다");
    }
  }, 2000);
}

isPositive(
  10,
  (res) => {
    console.log("성공적으로 수행됨 : ", res);
  },
  (err) => {
    console.log("실패 하였음 : ", err);
  }
);


promise 이용버전으로!
function isPositive(number, resolve, reject) {
  setTimeout(() => {
    if (typeof number === "number") {
      //성공 -> resolve
      resolve(number >= 0 ? "양수" : "음수");
    } else {
      //실패 -> reject
      reject("주어진 값이 숫자형 값이 아닙니다");
    }
  }, 2000);
}

function isPositiveP(number) {
  const executor = (resolve, reject) => {
    //실행자 - 비동기작업을 실질적으로 수행하는 수행자
    setTimeout(() => {
      if (typeof number === "number") {
        //성공 -> resolve
        console.log(number);
        resolve(number >= 0 ? "양수" : "음수");
      } else {
        //실패 -> reject
        reject("주어진 값이 숫자형 값이 아닙니다");
      }
    }, 2000);
  };

  const asyncTask = new Promise(executor); //비동기작업 자체인 Promise를 저장할 상수 asyncTask를 만들고 Promise객체의 생성자로 비동기작업의 실질적인 실행자함수 executor를 넘겨주게 되면 executor함수가 바로 수행이 된다.
  return asyncTask;
}

// isPositiveP(101);
const res = isPositiveP(101);

res
  .then((res) => {
    console.log("작업 성공 : ", res);
  })
  .catch((err) => {
    console.log("작업 실패 : ", err);
  });


----이제 프로미스 이용해서 콜백지옥 탈출하기
콜백지옥 탈출! ----
예시코드
function taskA(a, b, cb) {
  setTimeout(() => {
    const res = a + b;
    cb(res);
  }, 3000);
}

function taskB(a, cb) {
  setTimeout(() => {
    const res = a * 2;
    cb(res);
  }, 1000);
}

function taskC(a, cb) {
  setTimeout(() => {
    const res = a * -1;
    cb(res);
  }, 2000);
}

taskA(3, 4, (a_res) => {
  console.log("tastA : ", a_res);
  taskB(a_res, (b_res) => {
    console.log("taskB : ", b_res);
    taskC(b_res, (c_res) => {
      console.log("taskC : ", c_res);
    });
  });
});

/ --- Promise 객체로 전환 -----
function taskA(a, b) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const res = a + b;
      resolve(res);
    }, 3000);
  });
}

function taskB(a) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const res = a * 2;
      resolve(res);
    }, 1000);
  });
}

function taskC(a) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const res = a * -1;
      resolve(res);
    }, 2000);
  });
}

//버전4 중간 끊어쓰기
const bPromiseResult = taskA(5, 1).then((a_res) => {
  console.log("A RESULT : ", a_res);
  return taskB(a_res);
});

console.log("a;sdifjsleijf");
console.log("a;sdifjsleijf");
console.log("a;sdifjsleijf");
console.log("a;sdifjsleijf");

bPromiseResult
  .then((b_res) => {
    console.log("B RESULT : ", b_res);
    return taskC(b_res);
  })
  .then((c_res) => {
    console.log("C RESULT : ", c_res);
  });

버전3
taskA(5, 1)
  .then((a_res) => {
    console.log("A RESULT : ", a_res);
    return taskB(a_res);
  })
  .then((b_res) => {
    console.log("B RESULT : ", b_res);
    return taskC(b_res);
  })
  .then((c_res) => {
    console.log("C RESULT : ", c_res);
  });

버전2
taskA(5, 1).then((a_res) => {
  console.log("A RESULT : ", a_res);
  taskB(a_res).then((b_res) => {
    console.log("B RESULT : ", b_res);
    taskC(b_res).then((c_res) => {
      console.log("C RESLT : ", c_res);
    });
  });
});
버전1
taskA(3, 4, (a_res) => {
  console.log("tastA : ", a_res);
  taskB(a_res, (b_res) => {
    console.log("taskB : ", b_res);
    taskC(b_res, (c_res) => {
      console.log("taskC : ", c_res);
    });
  });
});





async

function hello() {
  return "hello";
}

async function helloAsync() {
  return "hello Async";
}

console.log(hello());
console.log(helloAsync());


async then 사용

function hello() {
  return "hello";
}

async function helloAsync() {
  return "hello Async";
}

helloAsync().then((res) => {
  console.log(res);
});

await

await하기 전 delay함수 만들자

function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, ms);
  });
}

3초기다렸다 반환함
function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function helloAsync() {
  return delay(3000).then(() => {
    return "hello Async";
  });
}

helloAsync().then((res) => {
  console.log(res);
});

3초기다렷다 반환할건데 코드가 너무 거창해 이럴때 await 이용
await
function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function helloAsync() {
  await delay(3000);
  return "hello async";
}

helloAsync().then((res) => {
  console.log(res);
});

await 에 메인함수 추가
function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function helloAsync() {
  await delay(3000);
  return "hello async";
}

async function main() {
  const res = await helloAsync();
  console.log(res);
}

main();




//API 호출
let response = fetch("https://jsonplaceholder.typicode.com/posts").then(
  (res) => {
    console.log(res);
  }
);

//json
async function getData() {
  let rawResponse = await fetch("https://jsonplaceholder.typicode.com/posts");
  let jsonResponse = await rawResponse.json();
  console.log(jsonResponse);
}

getData();

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함