728x90

1. JavaScript Engine

Call Stack(호출 스택) : 코드들이 짜여진 순서대로 한 줄 한 줄 들어가서 실행되는 공간(single threaded : 한 번에 코드 한번 수행 가능)

Heap : 변수, 함수 등이 할당되는 공간

 

2. Web APIs

setTimeout과 같은 비동기 함수들(APIs)이 정의되어 있는 영역

비동기 함수들이 Call Stack에 들어오면 Web API 영역으로 이동된다고 생각하자. 

이러한 비동기 함수들은 작업이 완료되면 callback 함수를 callback queue에 추가한다. 

 

3. Callback Queue

비동기 함수 작업이 완료된 후, 실행이 되기 위해 다시 Call Stack에 들어가기 전에 대기하는 영역.

해당 함수가 어떤 형태이냐에 따라서 대기 순서가 바뀌는데 순서는 아래와 같다.

1. Microtask Queue(Job Queue) : Promise 함수

2. Animation Frames

3. Task Queue(Event Queue) : setTimeout 함수

console.log(1);

setTimeout(() => console.log("setTimeout"));

Promise.resolve() //
  .then(() => console.log("Promise"));

console.log(2);

// 결과값
// 1
// 2
// "Promise"
// "setTimeout"

 

4. Event Loop

call stack에 작업중인 코드가 있는지 없는지 확인하는 과정.

call stack에 작업중인 코드가 없다면, callback queue에 대기하고 있던 작업들(콜백 함수)을 꺼내와서 call stack에 넘겨주는 역할을 한다.

 

5. JavaScript 내부 동작 원리 간단 정리

JavaScript는 기본적으로 웹 페이지를 작동시키기 위한 프로그래밍 언어이다. 웹페이지는 거의 즉각적이어야 한다.

JavaScript는 동기적으로 작동한다. 한 줄 한 줄(call stack).

그런데 즉각적으로 수행되지 못하는 코드들이 있다.(setTimeout, promise 등등)

그래서 JavaScript는 시간이 오래 걸리는 작업들을 Web APIs에게 넘겨버렸다. 

이러한 코드들은 작업이 완료되면 콜백함수를 callback queue에 추가한다. 

callback queue에 들어온 콜백함수들이 call stack에 들어가서 실행되기 위해서는 call stack에서 작업 중인 코드가 있는지 없는지 확인이 필요하다.

이러한 확인 절차를 거쳐 call stack에 아무것도 없을때 콜백 함수를 call stack에 추가해주는 것이 바로 event loop다. 

 

참고 자료

자바스크립트와 이벤트 루프

우리밋_woorimIT

코딩애플

반응형
728x90

1. 동기(synchronous)와 비동기(asynchronous)

동기란, 호이스팅(선언이 제일 위로 올라가는 것)이 된 이후부터 코드가 작성된 순서대로 작동한다는 의미이다. 

동기란 말을 처음 들었을 때는 동기화란 단어가 생각이 나서 "어떤 작업이 동시에 같이 일어나는 것인가?"라 생각을 했었는데, 전혀 다르다.

반면 비동기는 JavaScript의 동기적인 특성인 코드가 작성된 순서를 따르지 않고, 특정 요청에 의해 해당 코드에 지연이 발생하더라도 기다리지 않고 바로 이어서 다음 코드를 실행한다는 의미이다. 

// Synchronous
function first() {
  console.log("first"); // 첫번째로 실행되고,
}
function second() {
  console.log("second"); // 이어서 바로 실행된다. 
}
first()
second()
	
// Asynchronous
function first() {
  setTimeout(() => console.log(first), 5000); 
  // first 함수가 호출되고, 5초 동안 기다린 다음 결과값을 출력하고, 그 다음으로 second 함수가 실행되는게 아니다.
}
function second() {
  console.log("second"); 
  // first 함수가 호출되고, 5초의 시간이 흐르는 사이에 second 함수를 실행하고, 이후에 first 함수의 결과값이 출력된다.
}
first()
second()

 

2. callback(콜백)

callback 함수는 다른 함수가 실행을 끝낸 뒤 실행되는 즉, call back 되는 함수를 말한다.

함수의 parameter(매개변수)로 들어가서 실행되는 함수이다.

// Synchronous callback
function synchronousPrint(print) {
  print();
}
synchronousPrint(() => console.log("hello")); 
// hello를 출력하는 함수를 인자(argument)로 synchronous 함수에 전달 ==> 곧바로 synchronous 함수 실행(동기)

// Asynchronous callback
function asynchronousPrint(print, timeout) {
  setTimeout(print, timeout);
}
asynchronosPrint(() => console.log("hello"), 2000); 
// hello를 출력하는 함수를 인자(argument)로 asynchronous 함수에 전달 ==> 2초 후 asynchronous 함수 실행(비동기)

callback hell(콜백지옥)의 문제점 

1. 가독성이 떨어진다. => 어디서 어떻게 연결되어지는지 한눈에 알아보기 힘들다. 

2. 디버깅, 에러 분석, 유지/보수가 어렵다. 1번 이유때문.

 

3. Promise

Promise란?

JavaScript에서 제공하는 비동기를 간편하게 처리할 수 있도록 도와주는 object(객체)

네트워크 통신을 하거나, 파일을 읽어오는 행위 등 시간이 걸리는 일들은 promise를 만들어서 비동기적(병렬로 처리한다고 이해하면 쉬울 것 같다.)으로 처리하는 것이 좋다. 

Promise의 state는 뭘까?

promise의 state란 promise의 처리 과정을 의미한다.

기능이 수행 중인지(pending), 완료가 되어서 성공했는지(fulfilled), 실패했는지(rejected)를 나타내는 상태

Producer, Consumers란?

// 1. Producer(원하는 기능을 수행해서 해당하는 데이터를 만들어낸다.)
// Promise가 생성되면 자동적으로 실행된다.
const promise = new Promise((resolve, reject) => {
  console.log("doing somthing...");
  setTimeout(() => {
    resolve("Hello, World!"); // 콜백 함수의 인자 resolve를 호출하면 이행(fulfilled) 상태가 된다.
    // reject(new Error("no network")); // reject를 호출하면 실패(rejected) 상태가 된다. 
  }, 2000);
});

// 2. Consumers(원하는 데이터를 소비한다): then, catch, finally
promise
  .then((value) => {
    console.log(value);
  }) // 이행(fulfilled) 상태가 되면 then()을 이용하여 처리 결과 값을 받는다. 
  .catch((error) => {
    console.log(error);
  }) // 실패(rejected) 상태가 되면 catch()를 이용하여 처리 결과 값을 받는다. 
  .finally(() => {
    console.log("Done");
  }); // promise 이행/실패에 상관없이 마지막에 호출되어진다.

Promise chaining이란?

여러 개의 promise를 연결하는 것.

const fetchNumber = new Promise((resolve, reject) => {
  setTimeout(() => resolve(1), 1000);
}); // 이행 상태가 되어 1초뒤 resolve에 값이 들어온다. 

fetchNumber
  .then((num) => num * 2) // num parameter(매개변수)에 1이 들어오고 해당 콜백함수를 수행한 결과 값 2를 리턴한다.
  .then((num) => num * 3) // num parameter(매개변수)에 2가 들어오고 해당 콜백함수를 수행한 결과 값 6을 리턴한다.
  .then((num) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(num - 1), 1000);
    });
  }) // 새로운 promise를 만들어 1초 뒤 resolve에 5가 들어온다. 
  .then((num) => console.log(num)); // num parameter(매개변수)에 5가 들어오고 해당 콜백함수를 수행한다.

 

4. async/await

async와 await 이란? 

깔끔하게 promise를 사용할 수 있는 방법

Syntactic sugar

기능은 동일하지만 더 간결한 코드를 사용함으로써 직관성/편의성을 높여주는 프로그래밍 문법

ex) 삼항 연산자(Conditional (ternary) operator), 애로우 함수(arrow function), async 등등

async 사용 방법

// 기존 promise 사용 방법
function fetchUser() {
  return new Promise((resolve, reject) => {
    // do network request in 10 secs...
    resolve("ellie");
  });
}

// async 사용 방법(async = Syntactic sugar), 함수 앞에 async라는 키워드만 넣어주면 끝.
async function fetchUser() {
  // do network request in 10 secs...
  return "ellie";
}

const user = fetchUser();
user.then(console.log);
console.log(user);

await 사용 방법

// delay를 주는 promise 생성
function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

// 1초뒤 🍎를 받아오는 promise를 async 기능을 사용해서 생성
async function getApple() { // await 키워드는 async가 붙은 함수 안에서만 사용 가능
  await delay(1000);
  return "🍎";
}

// 1초뒤 🍌를 받아오는 promise를 async 기능을 사용해서 생성
async function getBanana() { 
  await delay(1000);
  return "🍌";
}

// 기존 promise를 사용해서 결과 값을 받아오는 방법(callback 지옥과 다를바 없다.)
function pickFruits() {
  return getApple().then((apple) => {
    return getBanana().then((banana) => `${apple} + ${banana}`);
  });
}

// await를 사용해서 결과 값을 받아오는 방법
async function pickFruits() {
  // JavaScript 특성상 동기적으로 🍎, 🍌의 promise를 실행할텐데,(2초가 걸리겠지)
  // 둘 사이의 연관성이 없다면 굳이 동기적으로 받아올 필요가 없다.
  // 따라서 Promise가 생성되면 자동적으로 실행되는 특징을 이용해서 변수(아래 두줄)를 생성해준다.
  // 두 함수가 동시에 실행되므로 시간 단축!(1초!)
  const applePromise = getApple();
  const bananaPromise = getBanana();
  const apple = await applePromise;
  const banana = await bananaPromise;
  return `${apple} + ${banana}`;
}

// 유용한 promise API: Promise.all(모든 promise들이 병렬적으로 작동해서 배열에 전달된다.)
function pickAllFruits() {
  return Promise.all([getApple(), getBanana()]) //
    .then((fruits) => fruits.join(" + "));
}

// 유용한 promise API: Promise.race(배열에 가장 먼저 전달된 promise 값을 받아온다.)
function pickOnlyOne() {
  return Promise.race([getApple(), getBanana()]);
}

 

참고 자료

드림 코딩 유튜브 - 자바스크립트 11~13

Evans Library

[번역] JavaScript: 도대체 콜백이 뭔데?

 

반응형
728x90

1. sessionStorage란?

sessionStorage에 대한 자세한 설명은 아래의 두 사이트를 참고.

쓸데없는 코딩하기
 

[javascript] 세션 스토리지 알고 사용하기

관련지식 javascript, storage, session storage, polyfill 사용자가 로그인을 하고 로그아웃을 할 때까지만 사용되어야 하는 값은 임시적으로 필요하지만 로그인 중에는 지속성 있게 유지가 될 필요가 있습

sub0709.tistory.com

모던 JavaScript 튜토리얼
 

localStorage와 sessionStorage

 

ko.javascript.info

 

2. sessionStorage 간단 사용

아래 그림과 같이 input tag에 댓글을 달면 로그인 시 사용한 이메일 정보(sessionStorage)와 댓글이 입력되는 웹페이지를 구현한다고 했을 때, login.html에서 수집한 이메일 정보를 review.html에서 사용하기 위해서는 이메일 정보가 지속성 있게 유지될 필요가 있다. 

review.html 페이지
login.html 페이지

sessionStorage 객체를 이용하면 이를 손쉽게 구현할 수 있다.

login.html과 연동된 login.js에 아래와 같은 코드를 입력하고, 

// login.js

let id = document.getElementById("emailInput"); 
// 이메일정보가 입력되는 input tag의 id(혹은 class)를 불러온다.

sessionStorage.setItem("ID", id.value);
// sessionStorage에 해당 정보의 값을 저장한다.

댓글이 작성될 review.html과 연동된 review.js에 아래와 같은 코드를 입력한다. 이 후에 해당 값을 원하는 대로 사용하면 끝!

// review.js

let yourID = sessionStorage.getItem("ID");
// sessionStorage에 저장된 이메일 정보 값을 review.js에서 불러온다.

 

개발자 도구에서 살펴보면 아래 그림과같이 Application 탭의 Session Storage에 해당 값이 저장되어 있는 것을 확인할 수 있다. 

반응형
728x90

13. 비동기의 꽃 JavaScript async 와 await 그리고 유용한 Promise APIs | 프론트엔드 개발자 입문편 (JavaScript ES6)

// async & await
// clear style of using promise :)

// 1. async
// function fetchUser() {
//   return new Promise((resolve, reject) => {
//     // do network request in 10 secs...
//     resolve("ellie");
//   });
// }

async function fetchUser() {
  // do network request in 10 secs...
  return "ellie";
}

const user = fetchUser();
user.then(console.log);
console.log(user);

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

async function getApple() {
  await delay(2000);
  return "🍎";
}

async function getBanana() {
  await delay(1000);
  return "🍌";
}

// function pickFruits() {
//   return getApple().then((apple) => {
//     return getBanana().then((banana) => `${apple} + ${banana}`);
//   });
// }

async function pickFruits() {
  const applePromise = getApple();
  const bananaPromise = getBanana();
  const apple = await applePromise;
  const banana = await bananaPromise;
  return `${apple} + ${banana}`;
}

pickFruits().then(console.log);

// 3. useful Promise APIs
function pickAllFruits() {
  return Promise.all([getApple(), getBanana()]).then((fruits) =>
    fruits.join(" + ")
  );
}

pickAllFruits().then(console.log);

function pickOnlyOne() {
  return Promise.race([getApple(), getBanana()]);
}

pickOnlyOne().then(console.log);
반응형
728x90

12. 프로미스 개념부터 활용까지 JavaScript Promise | 프론트엔드 개발자 입문편 (JavaScript ES6)

// promise.js

"use strict";

// Promise is a JavaScript object for asynchronous operation.
// State: pending -> fulfilled or rejected
// Producer vs Comsumer

// 1. Producer
// when new Promise is created, the executor runs automatically.
const promise = new Promise((resolve, reject) => {
  // doing some heavy work (network, read files)
  console.log("doing somthing...");
  setTimeout(() => {
    resolve("ellie");
    // reject(new Error("no network"));
  }, 2000);
});

// 2. Consumers: then, catch, finally
promise //
  .then((value) => {
    console.log(value);
  })
  .catch((error) => {
    console.log(error);
  })
  .finally(() => {
    console.log("Done");
  });

//   3. Promise chaining
const fetchNumber = new Promise((resolve, reject) => {
  setTimeout(() => resolve(1), 1000);
});

fetchNumber
  .then((num) => num * 2)
  .then((num) => num * 3)
  .then((num) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(num - 1), 1000);
    });
  })
  .then((num) => console.log(num));

//   4. Error Handling
const getHen = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => resolve("Chicken"), 1000);
  });
const getEgg = (hen) =>
  new Promise((resolve, reject) => {
    // setTimeout(() => resolve(`${hen} => Egg`), 1000);
    setTimeout(() => reject(new Error(`error! ${hen} => Egg`)));
  });
const cook = (egg) =>
  new Promise((resolve, reject) => {
    setTimeout(() => resolve(`${egg} => Egg fry`), 1000);
  });

getHen() //
  //   .then((hen) => getEgg(hen))
  .then(getEgg)
  //   .then((egg) => cook(egg))
  .catch((error) => {
    return "Bread";
  })
  .then(cook)
  //   .then((meal) => console.log(meal));
  .then(console.log)
  .catch(console.log);
// callback-to-promise.js

// Callback Hell example
class UserStorage {
  loginUser(id, password) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (
          (id === "ellie" && password === "dream") ||
          (id === "coder" && password === "academy")
        ) {
          resolve(id);
        } else {
          reject(new Error("not found"));
        }
      }, 2000);
    });
  }

  getRoles(user) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (user === "ellie") {
          resolve({ name: "ellie", role: "admin" });
        } else {
          reject(new Error("no access"));
        }
      }, 1000);
    });
  }
}

const userStorage = new UserStorage();
const id = prompt("enter your id");
const password = prompt("enter your password");
userStorage //
  .loginUser(id, password)
  .then(userStorage.getRoles)
  .then((user) => alert(`Hello ${user.name}, you have a ${user.role} role`))
  .catch(console.log);
반응형
728x90

11. 비동기 처리의 시작 콜백 이해하기, 콜백 지옥 체험 😱 JavaScript Callback | 프론트엔드 개발자 입문편 (JavaScript ES6)

"use strict";

// JavaScript is synchronous.
// Execute the code block in order after hoisting.
// hoisting: var, function declaration // 변수나 함수를 제일 위로 끌어올려 주는 것
console.log("1"); // 동기
// setTimeout(function () {
//   console.log("2");
// }, 1000);
setTimeout(() => console.log("2"), 1000); // 비동기
console.log("3"); // 동기

// Synchronous callback
function printImmediately(print) {
  print();
}
printImmediately(() => console.log("hello")); // 동기

// Asynchronous callback
function printWithDelay(print, timeout) {
  setTimeout(print, timeout);
}
printWithDelay(() => console.log("async callback"), 2000); // 비동기

// Callback Hell example
class UserStorage {
  loginUser(id, password, onSuccess, onError) {
    setTimeout(() => {
      if (
        (id === "ellie" && password === "dream") ||
        (id === "coder" && password === "academy")
      ) {
        onSuccess(id);
      } else {
        onError(new Error("not found"));
      }
    }, 2000);
  }

  getRoles(user, onSuccess, onError) {
    setTimeout(() => {
      if (user === "ellie") {
        onSuccess({ name: "ellie", role: "admin" });
      } else {
        onError(new Error("no access"));
      }
    }, 1000);
  }
}

const userStorage = new UserStorage();
const id = prompt("enter your id");
const password = prompt("enter your password");
userStorage.loginUser(
  id,
  password,
  (user) => {
    userStorage.getRoles(
      user,
      (userWithRoles) => {
        alert(
          `Hello ${userWithRoles.name}, you have a ${userWithRoles.role} role`
        );
      },
      (error) => {
        console.log(error);
      }
    );
  },
  (error) => console.log(error)
);
반응형
728x90

10. JSON 개념 정리 와 활용방법 및 유용한 사이트 공유 JavaScript JSON | 프론트엔드 개발자 입문편 (JavaScript ES6)

// JSON
// JavaScript Object Notation

// 1. Object to JSON
// stringfy(obj)
let json = JSON.stringify(true);
console.log(json);

json = JSON.stringify(["apple", "banana"]);
console.log(json);

const rabbit = {
  name: "tori",
  color: "white",
  size: null,
  birthDate: new Date(),
  //   symbol: Symbol("id"), // Symbol은 JSON에 포함되지 않는다.
  jump: () => {
    console.log(`${this.name} can jump!`);
  },
};

json = JSON.stringify(rabbit);
console.log(json);

json = JSON.stringify(rabbit, ["name", "color", "size"]);
console.log(json);

console.clear();
json = JSON.stringify(rabbit, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  //   return value;
  return key === "name" ? "ellie" : value;
});
console.log(json);

// 2. JSON to Object
// parse(json)
console.clear();
json = JSON.stringify(rabbit);
const obj = JSON.parse(json, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  //   return value;
  return key === "birthDate" ? new Date(value) : value; // string을 다시 object로..
});
console.log(obj);
rabbit.jump();
// obj.jump(); // JSON으로 변환될때 함수는 포함되지 않는다.

console.log(rabbit.birthDate.getDate());
console.log(obj.birthDate.getDate()); // JSON으로 넘어가면서 string이 되었기 때문에, parse를 이용해 다시 object로 넘어와도 여전히 string이다.
반응형
728x90

9. 유용한 10가지 배열 함수들. Array APIs 총정리 | 프론트엔드 개발자 입문편 ( JavaScript ES6)

// Q1. make a string out of an array
{
  const fruits = ["apple", "banana", "orange"];
  // di it yourself!
  // console.log(fruits.toString()); // .join과 .toString의 차이는 구분자(seperator)
  // answer
  const result = fruits.join(" and ");
  console.log(result);
}

// Q2. make an array out of a string
{
  const fruits = "🍎, 🥝, 🍌, 🍒";
  // do it yourself!
  // const fruit = fruits.split(",");
  // console.log(fruit);
  // answer
  const fruit = fruits.split(",");
  console.log(fruit);
}

// Q3. make this array look like this: [5, 4, 3, 2, 1]
{
  const array = [1, 2, 3, 4, 5];
  // do it yourself!
  // const reverseArray = array.reverse();
  // console.log(reverseArray);
  // answer
  const reverseArray = array.reverse();
  console.log(reverseArray);
  console.log(array); // 원래 배열도 바뀐다.
}

// Q4. make new array without the first two elements
{
  const array = [1, 2, 3, 4, 5];
  // do it yourself!
  // const result = array.slice(2);
  // const resultNew = array.slice(2, 5);
  // console.log(result);
  // console.log(resultNew);
  // // answer
  const result = array.slice(2, 5);
  console.log(result);
  console.log(array);
}

// -------------------------------------------------------------
class Student {
  constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  }
}
const students = [
  new Student("A", 29, true, 45),
  new Student("B", 28, false, 80),
  new Student("C", 30, true, 90),
  new Student("D", 40, false, 66),
  new Student("E", 18, true, 88),
];

// Q5. find a student with the score 90
{
  // do it yourself!
  // for (let i = 0; i < students.length; i++) {
  //   if (students[i].score === 90) {
  //     console.log(students[i]);
  //   }
  // }
  // answer
  // const result = students.find(function (value) {
  //   return value.score === 90;
  // });
  const result = students.find((value) => value.score === 90);
  console.log(result);
}

// Q6. make an array of enrolled students
{
  // do it yourself!
  // const result = students.filter((value) => value.enrolled === true);
  // console.log(result);
  // // answer
  const result = students.filter((student) => student.enrolled === true);
  console.log(result);
}

// Q7. make an array containing only the students' scores
// result should be: [45, 80, 90, 66, 88]
{
  // do it yourself!
  // let result = [];
  // for (let i = 0; i < students.length; i++) {
  //   result.push(students[i].score);
  // }
  // console.log(result);
  // answer
  const result = students.map((student) => student.score);
  console.log(result);
}

// Q8. check if there is a student with the score lower than 50
{
  // do it yourself!
  // const result = students.some((student) => student.score < 50);
  // console.log(result);
  // answer
  const result = students.some((student) => student.score < 50);
  console.log(result);

  const result2 = !students.every((student) => student.score >= 50);
  console.log(result2);
}

// Q9. compute students' average score
{
  //do it yourself!
  // let result = 0;
  // for (let i = 0; i < students.length; i++) {
  //   result += students[i].score;
  // }
  // console.log(result / 5);
  // answer
  // const result = students.reduce((prev, curr) => {
  //   console.log("----------");
  //   console.log(prev);
  //   console.log(curr);
  //   return prev + curr.score;
  // }, 0);
  const result = students.reduce((prev, curr) => prev + curr.score, 0);
  console.log(result / students.length);
}

// Q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88'
{
  // do it yourself!
  // const result = students.map((student) => student.score);
  // const resultArray = result.join();
  // console.log(resultArray);
  // answer
  const result = students
    .map((student) => student.score)
    // .filter((score) => score >= 50)
    .join();
  console.log(result);
}

// Bonus! do Q10 sorted in ascending order
// result should be: '45, 66, 80, 88, 90'
{
  // do it yourself!
  // const result = students
  //   .map((student) => student.score)
  //   .sort((a, b) => a - b)
  //   .join();
  // console.log(result);
  // answer
  const result = students
    .map((student) => student.score)
    .sort((a, b) => a - b)
    .join();
  console.log(result);
}
반응형
728x90

8. 배열 제대로 알고 쓰자. 자바스크립트 배열 개념과 APIs 총정리 | 프론트엔드 개발자 입문편 (JavaScript ES6 )

"use strict";

// Array

// 1. Declaration
const arr1 = new Array();
const arr2 = [];

// 2. Index position
const fruits = ["apple", "banana"];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
console.log(fruits[fruits.length - 1]);
console.clear();
// 3. Looping over an array
// print all fruits
// a. for
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

// b. for of
for (let fruit of fruits) {
  console.log(fruit);
}

// c. for each
// fruits.forEach(function (fruit, index) {
//   console.log(fruit, index);
// });

// fruits.forEach((fruit, index) => {
//   console.log(fruit, index);
// });

// fruits.forEach((fruit, index) => console.log(fruit, index));
fruits.forEach((fruit) => console.log(fruit));

// 4. Addtion, deletion, copy
// push: add an item to the end
fruits.push("strawberry", "peach");
console.log(fruits);

// pop: remove an item from the end
fruits.pop();
fruits.pop();
console.log(fruits);

// unshift: add an item to the beginning
fruits.unshift("strawberry", "peach");
console.log(fruits);

// shift: remove an item from the beginning
fruits.shift();
fruits.shift();
console.log(fruits);

// note!! shift, unshift are slower than pop, push: 나머지 전체가 움직여야 하기 때문에
// splice: remove an item by index position
fruits.push("strawberry", "peach", "lemon");
console.log(fruits);
fruits.splice(1, 1);
console.log(fruits);
fruits.splice(1, 1, "greenapple", "watermelon");
// fruits.splice(1, 0, "greenapple", "watermelon");
console.log(fruits);

// combine two arrays
const fruits2 = ["coconut", "durian"];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

// 5. Searching
// indexOf: find the index
console.clear();
console.log(fruits);
console.log(fruits.indexOf("apple"));
console.log(fruits.indexOf("lemon"));
console.log(fruits.indexOf("durian")); // 찾는 값이 없을 경우 -1을 출력

// includes
console.log(fruits.includes("durian"));
console.log(fruits.includes("peach"));

// lastIndexOf
console.clear();
fruits.push("apple");
console.log(fruits);
console.log(fruits.indexOf("apple")); // 첫번째 값의 index만 출력
console.log(fruits.lastIndexOf("apple")); // 마지막 값의 index만 출력
반응형
728x90

객체(object)란 무엇이며 필요한 이유는?

  • 객체의 정의
    1. 객체는 관련된 데이터와 함수(일반적으로 여러 데이터와 함수로 이루어지는데, 객체 안에 있을 때는 보통 property와 method라고 부른다.)의 집합이다. 
    2. 여러 속성을 하나의 변수에 저장할 수 있도록 해주는 데이터 형식
  • 객체가 필요한 이유
    1. 객체는 서로 연관된 데이터들의 집합이기 때문에 해당 데이터들에 대한 코드의 유지 보수가 편한다. 
    2. 배열 내 요소들은 인덱스로 구분되는 반면, 객체의 데이터(property, method)는 key와 value 및 함수로 구성되기 때문에 데이터를 더욱 직관적 알아볼 수 있다. 

객체에서 속성(property), 키(key), 값(value), 메서드(method)

// 객체(Object)
const koreaInformation = { // koreaInformation = 객체명
  Capital: "Seoul", // Capital = property(key), "Seoul" = property(value)
  "Officail Languages": "Korean", // key는 문자열만 가능, key에 띄어쓰기가 들어간 경우 따옴표 사용
  President: "Moon Jae-in",
  Area: "100,363km^2",
  gdp() { // 객체안에 있는 함수는 특별히 메소드(method)라고 부른다
    console.log("2021 estimate: $1.806 trillon");
  },
};

 

참고

반응형
728x90

7. 오브젝트 넌 뭐니? | 프론트엔드 개발자 입문편 (JavaScript ES6)

// Object
// one of the JavaScript's data types.
// a collection of related data and/or functionality.
// Nearly all objects in JavaScript are instance of Object
// objeft = { key : value}

// 1. Literals and properties
const obj1 = {}; // 'object literal' syntax
const obj2 = new Object(); // 'object constructor' syntax

function print(person) {
  console.log(person.name);
  console.log(person.age);
}

const ellie = { name: "ellie", age: 4 };
print(ellie);

// with JavaScript magic (dynamically typed language)
// can add properties later
ellie.hasJob = true; // 비추천!
console.log(ellie.hasJob);

// can delete properties later
delete ellie.hasJob;
console.log(ellie.hasJob);

// 2. Computed properties
// key should be always string
console.log(ellie.name); // coding하는 그 순간 key에 해당하는 value를 받아오고 싶을 때 사용한다.
console.log(ellie["name"]); // 정확히 어떤 key가 필요한지 모를 때(즉, runtime에서 결정될 때) 사용한다.
ellie["hasJob"] = true;
console.log(ellie.hasJob);

function printValue(obj, key) {
  //   console.log(obj.key);
  console.log(obj[key]); // ['key']가 아니라 [key]를 사용 했다. 변수로 접근
}

printValue(ellie, "name");
printValue(ellie, "age");

// 3. Property value shorthand
const person1 = { name: "bob", age: 2 };
const person2 = { name: "steve", age: 3 };
const person3 = { name: "dave", age: 4 };
// const person4 = makePerson("ellie", 30);
const person4 = new Person("ellie", 30);
console.log(person4);
// function makePerson(name, age) {
//   return {
//     name: name,
//     age, // key와 value의 이름이 동일하다면 생략 가능
//   };
// }

// 4. Constructor Function
function Person(name, age) {
  // this = {};
  this.name = name;
  this.age = age;
  // return this;
}

// 5. in operator: property existence check (key in obj)
console.log("name" in ellie); // 해당하는 object안에 key가 있는지 확인
console.log("age" in ellie);
console.log("random" in ellie);
console.log(ellie.random);
console.log(ellie.name);
console.log(ellie["name"]);

// 6. for..in vs for..of
// for (key in obj)
console.clear(); // 이전 log들 삭제
for (key in ellie) {
  console.log(key);
}

// for (value of iterable)
const array = [1, 2, 4, 5];
// for (let i = 0; i < array.length; i++) {
//   console.log(array[i]);
// }

for (value of array) {
  console.log(value);
}

// 7. Fun cloning
// Object.assign(dest, [obj1, obj2, obj3...])
const user = { name: "ellie", age: 20 };
const user2 = user;
// user2.name = "coder";
console.log(user);

// old way
const user3 = {};
for (key in user) {
  user3[key] = user[key];
}
console.clear();
console.log(user3);

// new way 1
const user4 = {};
Object.assign(user4, user);
console.log(user4);

// new way 2
const user5 = Object.assign({}, user);
console.log(user5);

// another example
const fruit1 = { color: "red" };
const fruit2 = { color: "blue", size: "big" };
const mixed = Object.assign({}, fruit1, fruit2);
console.log(mixed["color"]);
console.log(mixed.color);
반응형
728x90
object[key]는 변수로 접근하지만, object.key 및 object['key']는 object(객체)의 property(key)에 접근한다. 

 

example 1

let num = {
  one: 1,
  two: 2,
};

let one = "two";

console.log(num.one); // result: 1 --> num object에서 one이라는 key의 value 값을 출력한다. 
console.log(num["one"]); // result: 1 --> num object에서 one이라는 key의 value 값을 출력한다. 
console.log(num[one]); // result: 2 --> one이라는 변수에는 num object의 two라는 key 값이 할당되었기 때문에(??뭔지 좀 이해가 안간다..) num object에서 two라는 key의 value 값을 출력한다.

example 2

const user = { name: "Steve", age: 4 };

function printValue(obj, key) {
  // console.log(obj.key); undefined --> user라는 object에는 'key'라는 key값이 없기 때문에 발생
  // console.log(obj["key"]); undefined --> 위와 동일
  console.log(obj[key]); // ['key']가 아니라 [key]를 사용 했다. 변수로 접근. 즉, 아래 printValue의 "name"과 "age"에 해당하는 key의 value 값을 출력한다.
}

printValue(user, "name"); // result: Steve
printValue(user, "age"); // result: 4

 

반응형

+ Recent posts