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

Study Planner(Google Spredsheet)
Book Library(Notion)

 

Today Read Hours Total Read Hours
3.0 546.5

 


Today I Read

 

Book No. Hours
(Sum)
Title Author Date Pages IL BL
78 1.5
(7.5)
The Compound Effect Darren Hardy 2021.11.01 ~
ING
80~102/158 - -
79 0.0
(0.5)
P.S. I Still Love You(Audio) Jenny Han 2021.11.01 ~
ING
248 UG 4.3
80 1.5
(4.5)
Gathering Blue Lois Lowry 2021.11.03 ~
ING
55~79/210 MG+ 5.0

 


 

예전에 읽었던 The giver도 그렇고 지금 읽고 있는 Gathering Blue도 그렇고....Lois Lowry의 책은 뭐랄까..독특하다. SF 장르인 것 같은데 드러내진 않는다. 지금 읽은 부분까지 보면 The giver와 연결되는 것 같지도 않다.(그럼 왜 Giver Quartet 인거지..?) ....어라? 책 리뷰를 쓰고 있었네.암튼 요즘 영어는 그냥저냥 그렇다. 해외 유투버들이 맥북 M1프로 리뷰를 많이 해줘서 주구 장창 그거만 보고 듣고 있다. 그리고 역시나 들리는 부분만 들리고 안 들리는 데는 안 들린다. 물론 굳이 다시 돌려서 듣거나 하진 않는다. 올해 초에 영어공부를 시작했을때와 지금을 비교해 본다면 확실히 읽기는 어느 정도는 나아진 거 같긴 하다. 듣기도...조금은 더 잘 들린다. 
반응형
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

 

반응형
728x90

Study Planner(Google Spredsheet)
Book Library(Notion)

 

Today Read Hours Total Read Hours
1.5 543.5

 


Today I Read

 

Book No. Hours
(Sum)
Title Author Date Pages IL BL
78 1.0
(6.0)
The Compound Effect Darren Hardy 2021.11.01 ~
ING
67~80/158 - -
79 0.0
(0.5)
P.S. I Still Love You(Audio) Jenny Han 2021.11.01 ~
ING
248 UG 4.3
80 0.5
(3.0)
Gathering Blue Lois Lowry 2021.11.03 ~
ING
48~55/210 MG+ 5.0

 


 

ING
반응형
728x90

6. 클래스와 오브젝트의 차이점(class vs object), 객체지향 언어 클래스 정리 | 프론트엔드 개발자 입문편 (JavaScript ES6)

"use strict";
// Object-oriented programming
// class: template
// object: instance of a class
// JavaScript classes
// - introduced in ES6
// - syntactical sugar over prototype-based inheritance

// 1. Class declarations
class Person {
  // constructor
  constructor(name, age) {
    // fields
    this.name = name;
    this.age = age;
  }

  //   methods
  speak() {
    console.log(`${this.name}: hello!`);
  }
}

const ellie = new Person("ellie", 20);
console.log(ellie.name);
console.log(ellie.age);
ellie.speak();

// 2. Getter and Setters 방어적으로 만드는거
class User {
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

  get age() {
    return this._age;
  }

  set age(value) {
    // if (value < 0) {
    //   throw Error("age can not be negative");
    // }
    this._age = value < 0 ? 0 : value;
  }
}

const user1 = new User("Steve", "Jobs", -1);
console.log(user1.age);

// 3. Fields (public, private)
// Too soon!
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
class Experiment {
  publicField = 2;
  #privateField = 0; // 클래스 내부에서만 접근 가능
}

const experiment = new Experiment();
console.log(experiment.publicField);
console.log(experiment.privateField);

// 4. Static properties and methods
// Too soon!
class Article {
  static publisher = "Dream Coding";
  constructor(articleNumber) {
    this.articleNumber = articleNumber;
  }

  static printPublisher() {
    console.log(Article.publisher);
  }
}

const article1 = new Article(1);
const article2 = new Article(2);
console.log(Article.publisher);
Article.printPublisher();

// 5. Inheritance
// a way for one class to extend another class.
class Shape {
  constructor(width, height, color) {
    this.width = width;
    this.height = height;
    this.color = color;
  }

  draw() {
    console.log(`drawing ${this.color} color!`);
  }

  getArea() {
    return this.width * this.height;
  }
}

class Rectangle extends Shape {}
class Triangle extends Shape {
  draw() {
    super.draw();
    console.log("🔺");
  }
  getArea() {
    return (this.width * this.height) / 2;
  }

  toString() {
    return `Triangle: color: ${this.color}`;
  }
}

const rectangle = new Rectangle(20, 20, "blue");
rectangle.draw();
console.log(rectangle.getArea());

const triangle = new Triangle(20, 20, "red");
triangle.draw();
console.log(triangle.getArea());

// 6. Class checking: instanceOf
console.log(rectangle instanceof Rectangle); // true
console.log(triangle instanceof Rectangle); // false
console.log(triangle instanceof Triangle); // true
console.log(triangle instanceof Shape); // true
console.log(triangle instanceof Object); // true
console.log(triangle.toString());
반응형
728x90

Study Planner(Google Spredsheet)
Book Library(Notion)

 

Today Read Hours Total Read Hours
1.5 542.0

 


Today I Read

 

Book No. Hours
(Sum)
Title Author Date Pages IL BL
78 0.5
(5.0)
The Compound Effect Darren Hardy 2021.11.01 ~
ING
60~67/158 - -
79 0.0
(0.5)
P.S. I Still Love You(Audio) Jenny Han 2021.11.01 ~
ING
248 UG 4.3
80 1.0
(2.5)
Gathering Blue Lois Lowry 2021.11.03 ~
ING
29~48/210 MG+ 5.0

 


 

점점 게을러 지고 있다!!!
반응형
728x90

Study Planner(Google Spredsheet)
Book Library(Notion)

 

Today Read Hours Total Read Hours
2.0 540.5

 


Today I Read

 

Book No. Hours
(Sum)
Title Author Date Pages IL BL
78 1.5
(4.5)
The Compound Effect Darren Hardy 2021.11.01 ~
ING
35~60/158 - -
79 0.0
(0.5)
P.S. I Still Love You(Audio) Jenny Han 2021.11.01 ~
ING
248 UG 4.3
80 0.5
(1.5)
Gathering Blue Lois Lowry 2021.11.03 ~
ING
20~29/210 MG+ 5.0

 


 

ING
반응형
728x90

크롬 브라우저의 개발자 도구에서 아래와 같이 코드를 작성하면 조금 특이한 결과 값(?)이 나온다. 

 

개발자 도구에서의 console 창은 어떤 명령에 대한 "결과 값"을 표시해주는 역할을 하는데 printNew 변수를 선언한 문장(const printNew)은 그 자체로는 아무런 결과 값을 보여주지 않기 때문에 undefined(첫번째 빨간 상자)가 출력된다. 두 번째 빨간 상자의 undefined도 console.log() 문장에 대한 동일한 결과라고 볼 수 있다. 

그렇다면 초록색 상자는 무슨 의미일까?

초록색 상자의 undefined는 printNew 변수에 할당된 함수의 결과 값중 하나로 봐야 하는 것인가?? 함수가 실행되면 먼저 "print"가 출력되고, 이후에는 console.log("print"); 구문 자체에 대한 결과값으로 "undefined"가 출력된 것으로 이해를 해야 하는건지 궁금하다.

 

reference : Why does console.log say undefined, and then the correct value?(stackoverflow)

반응형
728x90

5. Arrow Function은 무엇인가 함수의 선언과 표현   프론트엔드 개발자 입문편(JavaScript ES6)

// Function
// - fundamental building block in the program
// - subprogram can be used multiple times
// - performs a task or calculates a value

// 1. Function declaration
// function name(parm1, param2) { body... return;}
// one function === one thing
// naming: doSomething, command, verb
// e.g. createCardAndPoint -> createCard, createPoint
// function is object in JS
"use strict";

function printHello() {
  console.log("Hello");
}
printHello();

function log(message) {
  console.log(message);
}

log("Hello@2");
log(1234);

// 2. Parameters
// premitive parameters: passed by value
// object parameters: passed by reference
function changeName(obj) {
  obj.name = "coder";
}
const ellie = { name: "ellie" };
changeName(ellie);
console.log(ellie);

// 3. Default parameter (added in ES6)
// function showMessage(message, from) {
//   if (from === undefined) {
//     from = "unknown";
//   }
//   console.log(`${message} by ${from}`);
// }
// showMessage("Hi!");
function showMessage(message, from = "unknown") {
  console.log(`${message} by ${from}`);
}

showMessage("Hi!");

// 4. Rest parameter (add in ES6)
function printAll(...args) {
  // ... 배열 형태로 전달한다.
  for (let i = 0; i < args.length; i++) {
    console.log(args[i]);
  }

  for (const arg of args) {
    console.log(arg);
  }

  args.forEach((arg) => console.log(arg));
}

printAll("dreaqm", "coding", "ellie");

// 5. Local scope (밖에서는 안이 보이지 않고, 안에서민 밖을 볼 수 있다.)
let globalMessage = "global"; // global variable
function printMessage() {
  let message = "hello";
  console.log(message); // local variable
  console.log(globalMessage);
  function printAnother() {
    console.log(message);
    let childMessage = "happy";
  }
  // console.log(childMessage); // error
  return undefined; // 생략 가능
}

printMessage();

// 6. Return a value
function sum(a, b) {
  return a + b;
}
const result = sum(1, 2); // 3
console.log(`sun: ${sum(1, 2)}`);

// 7. Early return, early exit
// bad
function upgradeUser(user) {
  if (user.point > 10) {
    // long upgrade logic...
  }
}

// good (조건이 맞지 않을 때는 바로 return 해서 함수를 종료하고 조건이 맞을때만 로직 실행하도록!)
function upgradeUser(user) {
  if (user.point <= 10) {
    return;
  }
  //long upgrade logic...
}

// First-class function
// functions are treated like any other variable
// can be assigned as a value to variable
// can be passed as an argument to other functions.
// can be returned by another function

// 1. Function expresstion
// a function declaration can be called earlier than it is defined. (hoisted) -> function print() {}
// a function expresstion is created when the execution reaches it. -> const print = funtcion () {}
const print = function () {
  // anonymous function
  console.log("print");
};
print();
const printAgain = print;
printAgain();
const sumAgain = sum;
console.log(sumAgain(1, 3));

// 2. Callback function using function expression
function randomQuiz(answer, printYes, printNo) {
  if (answer === "love you") {
    printYes();
  } else {
    printNo();
  }
}
// anonymous function
const printYes = function () {
  console.log("yes!");
};

// named function
// better debugging in debugger's stack traces
// recursions
const printNo = function print() {
  console.log("no!");
};

randomQuiz("wrong", printYes, printNo);
randomQuiz("love you", printYes, print);

// Arrow function
// always anonymous
// const simplePrint = function () {
//   console.log("simplePrint!");
// };

const simplePrint = () => console.log("simplePrint");
const add = (a, b) => a + b;
const simpleMuliply = (a, b) => {
  // do something more
  return a * b;
};

// IIFE: Immediately Invoked Function Expression
(function hello() {
  console.log("Hello!");
})();

// Fun Quiz time
// function caluate(command, a, b)
// command: add, substract, devide, multiply, remainder

function calculate(command, a, b) {
  if (
    command !== "add" &&
    command !== "substract" &&
    command !== "divide" &&
    command !== "multiply" &&
    command !== "remainder"
  ) {
    console.log("wrong!");
  } else if (command === "add") {
    console.log(`${command}: ${a} + ${b} =`, a + b);
  } else if (command === "substract") {
    console.log(`${command}: ${a} + ${b} =`, a - b);
  } else if (command === "divide") {
    console.log(`${command}: ${a} + ${b} =`, a / b);
  } else if (command === "multiply") {
    console.log(`${command}: ${a} + ${b} =`, a * b);
  } else if (command === "remainder") {
    console.log(`${command}: ${a} + ${b} =`, a % b);
  }
}

calculate("remainder", 5, 2);

// ellie's answer
function calculate(command, a, b) {
  switch (command) {
    case "add":
      return a + b;
    case "substract":
      return a - b;
    case "divide":
      return a / b;
    case "multiply":
      return a * b;
    case "remainder":
      return a % b;
    default:
      throw Error("unknown command");
  }
}

 

반응형
728x90

4. 코딩의 기본 operator, if, for loop 코드리뷰 팁 | 프론트엔드 개발자 입문편 (JavaScript ES6)

// 1. String concatenation
console.log("my" + " cat");
console.log("1" + 2);
console.log(`string literals: 1 + 2 = ${1 + 2}`);

// 2. Numeric operators
console.log(1 + 1); // add
console.log(1 - 1); // substract
console.log(1 / 1); // divide
console.log(1 * 1); // muliply
console.log(5 % 2); // remainder
console.log(2 ** 3); // exponentiation

// 3. Increment and decrement operators
let counter = 2;
const preIncrement = ++counter;
// counter = counter + 1;
// preIncrement = counter;
console.log(`preIncrement: ${preIncrement}, counter: ${counter}`);
const postIncrement = counter++;
// postIncrement = counter;
// counter = counter + 1;
console.log(`preIncrement: ${preIncrement}, counter: ${counter}`);
const preDecrement = --counter;
console.log(`preIncrement: ${preDecrement}, counter: ${counter}`);
const postDecrement = counter--;
console.log(`preIncrement: ${preDecrement}, counter: ${counter}`);

// 4. Assignment operators
let x = 3;
let y = 6;
x += y; // x = x + y;
x -= y;
x *= y;
x /= y;

// 5. Comparison operators
console.log(10 < 6); // less than
console.log(10 <= 6); // less than or equal
console.log(10 > 6); // greater than
console.log(10 >= 6); // greater than or equal

// 6. Logical operators: || (or), && (and), ! (not)
const value1 = false;
const value2 = 4 < 2;

// || (or), finds the first truthy value
console.log(`or: ${value1 || value2 || check()}`); // 심플한 코드를 먼저 실행하게끔 하자

// && (and), finds the first truthy value
console.log(`and: ${value1 && value2 && check()}`); // 심플한 코드를 먼저 실행하게끔 하자

// often used to compress long if-statment
// nullableObject && nullableObject.something
// if (nullableObject != null) {
//   nullableObject.something;
// }

function check() {
  for (let i = 0; i < 10; i++) {
    //wasting time
    console.log("🤩");
  }
  return true;
}

// ! (not)
console.log(!value1);

// 7. Equality
const stringFive = "5";
const numberFive = 5;

// == loose qeuality, with type conversion
console.log(stringFive == numberFive);
console.log(stringFive != numberFive);

// === strict qeuality, no type conversion
console.log(stringFive === numberFive);
console.log(stringFive !== numberFive);

// object equality by reference
const ellie1 = { name: "ellie" };
const ellie2 = { name: "ellie" };
const ellie3 = ellie1;
console.log(ellie1 == ellie2);
console.log(ellie1 === ellie2);
console.log(ellie1 === ellie3);

// equality - puzzler
console.log(0 == false); // true
console.log(0 === false); // false
console.log("" == false); // true
console.log("" === false); // false
console.log(null == undefined); //true
console.log(null === undefined); //false

// 8.  Conditional operators: if
// if, else if, else
const name = "Jongmin Choi";
if (name === "Jongmin Choi") {
  console.log("Welcome, Jongmin Choi!");
} else if (name === " coder") {
  console.log("You are amazing coder");
} else {
  console.log("unknown");
}

// 9. Ternary operator: ?
// condition ? value1 : value2
console.log(name === "Jongmin Choi" ? "yes" : "no"); // 간단히 쓸때만 쓰자

// 10. Switch statement
// use for multiple if checks
// use for enum-like value check
// use for multiple type checks in TS
const browser = "chrome";
switch (browser) {
  case "IE":
    console.log("go away!");
    break;
  case "chrome":
  case "Firefox": // 결과값이 같으면 같이 묶는다.
    console.log("love you!");
    break;
  default:
    console.log("same all!");
    break;
}

// 11. Loops
// while loop, while the condition is trythy,
// body code is executed.
let i = 3;
while (i > 0) {
  //   let j = [];
  console.log(`while: ${i}`);
  //   j.push(i);
  i--;
  //   console.log(j);
}

// do while loop, body code is executed first,
// then check the condition.
do {
  console.log(`dowhile: ${i}`);
  i--;
} while (i > 0);

// for loop, for(begin; condition; step)
for (i = 3; i > 0; i--) {
  console.log(`for: ${i}`);
}

for (let i = 3; i > 0; i = i - 2) {
  // inline variable declaration
  console.log(`inline variable for: ${i}`);
}

// nested loops (cpu에 부담이 간다 좋지 않다.)
for (let i = 0; i < 10; i++) {
  for (let j = 0; j < 10; j++) {
    console.log(`i: ${i}, j: ${j}`);
  }
}

// break, continue
// Q1. iterate from 0 to 10 and print only even numbers (use continue)
let evenNumbers = [];

for (let i = 1; i < 11; i++) {
  if (i % 2 === 1) {
    continue;
  }
  evenNumbers.push(i);
}

console.log(evenNumbers);

// Q2. iterate from 0 to 10 and print numbers until reaching 8 (use break)

let nums = [];

for (let i = 0; i < 11; i++) {
  if (i > 8) {
    break;
  }
  nums.push(i);
}

console.log(nums);
반응형
728x90

1. 배열(array)의 특징

  • 순서(index)가 존재하며 순차적으로 할당된다.
  • index를 이용한 무작위 접근(random access: 메모리의 주소만 알고 있으면 어디에서도 죽시 데이터를 읽어낼 수 있는 호출 방식)이 가능하기 때문에 검색이 빠르다.
  • 순서가 있기 때문에 자료의 삽입과 삭제가 비효율적이다.(자료의 삽입/삭제시 다음 항목 모든 요소의 이동이 필요해진다.)

2. 배열과 반복문을 함께 자주 사용하는 이유

반복문은 동일한 명령을 정해진 횟수만큼 반복하여 수행하도록 제어하는 명령문으로 구문(syntax)에는 주로 변수 증감을 위한 명령을 많이 사용하는데, 배열의 index가 해당 역할을 수행하기에 적합하기 때문에 배열과 반복문은 자주 함께 쓰인다. 

let myArray = [1,2,3,4,5,6,7,8,9,10]

for (i = 0; i < 10; i++) {
  myArray[i] += 1;
}

console.log(myArray); // result: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
반응형

+ Recent posts