20210213_JavaScript05 Object, Array

5 분 소요

JavaScript05

  • JavaScript에 대해 공부하기 위해서 유튜브 ‘드림코딩by엘리’ JavaScript 강의를 듣고 글을 쓰고 있다.
  • one of the JavaScript’s data types.
  • a collection of related data and/or functionality
  • Nearly all objects in JavaScript are instances of Object

  • 오브젝트가 없으면
    • 일일이 변수들을 선언해 주어야 하고 코드의 중복이 많아짐
    • 정리가 어려워 찾기가 어려움 (접근하기도 불편해짐)
    • 즉, 자료의 검색, 정렬, 삭제, 추가가 어려움
// old way (변수가 모두 따로 따로 정의)
const name = 'raccoon';
const age = 4;
print(name, age); 
// 접근하기 편하게 하기위해서 특정 함수정의하고 이용해서 접근
function print(name, age) {
    console.log(name);
    console.log(age);
}

// Object 활용
// Objcect -> 사전 형식의 데이터 타입
function print(person) {
    console.log(person.name);
    console.log(person.age);
}




1. Literals and properties (values, keys in python)

  • 신기하게도 JavaScript에서는 values를 literals라고 하고 properties를 keys라고 함
  • Oject는 사전형 구조임 object = { key : value};

object 만드는 법

  • object literal syntax -> {} 사용
  • object constructor syntax -> new Object()
    • Object라는 클래스를 new라는 constructor를 이용해서 생성
const obj1 = {}; // 'object literal' syntax
const obj2 = new Object(); // new라는 키워드로 생성`object constructor` syntax (class를 이용해서 만들수 있음)

const raccoon = {name: 'raccoon', age: 4}; 
// 클래스 생성 선언 없어도 바로 오브젝트 생성 가능
function print(person) {
    console.log(person.name);
    console.log(person.age);
}
print(raccoon);


Oject에서 property, literal 유연성

  • JavaScript는 dynamically typed language 이기 때문에 동적으로 type이 runtime(프로그램 동작시)때 결정됨
  • 선언된 상태에서도 propertym listeral에 접근해서 추가, 삭제, 변경 가능
const raccoon = {name: 'raccoon', age: 4};

raccoon.hasJob = true; // property를 추가 가능 (이미 정의 했음에도 불구하고)
console.log(raccoon.hasJob);

delete raccoon.hasJob; // 삭제도 가능
console.log(raccoon.hasJob);



2. Computed properties (계산된 key)

  • key should be always string
  • 접근 방법
    • properties(key)에 dot .을 통해서 변수 접근 가능함
      • (보통 정적으로 정해진 property의 이름을 이용하는 경우)
    • 동적으로 string 형태 받아 []를 통해 key에 접근 가능함
      • (동적으로 다양한 이름의 property를 받아 활용하고 싶을 때 []를 사용)
console.log(raccoon['name']);
raccoon['hasJob'] = true;
console.log(raccoon.hasJob);

function printValue(obj, key) {
    console.log(obj.key); // error 
    // obj안에 key라는 이름의 property가 들어 있는가 찾아보는 것임 (매개변수를 못받음)
    console.log(obj[key]) // 이렇게 넣음으로서 파라미터를 받아와서 응용가능 (동적으로 key의 value를 받고자 할때 사용가능)
}
printValue(raccoon, 'name'); 
printValue(raccoon, 'age'); 



3. Property value shorthand

  • object 생성시 동일한 key값을 계속해서 써서 생성해야하는 불편함이 생김
  • function을 정의 object 생성기를 만듬 -> 기능은 결국에 template기능인 class 와 같음

  • 과거 Object 생성시 key 중복 코딩
const person1 = { name: 'bob', age: 2};
const person2 = { name: 'steve', age: 3};
const person3 = { name: 'dave', age: 4};
// name, age를 계속 작성해야됨


  • 함수를 이용한 Object 생성 template
    • 함수안에 parameter 와 property이름을 같이해서 작성
    • 나중에 parameter을 생략해서 그냥 property이름만 넣으면 같게 해주는 기능이 생김
      function makePerson(name, age) {
      return {
          name, // name: name, (property이름과 parameter 이름이 같으면 생략해서 object 생성가능)
          age, // age: age,
      };
      }
      



4. Constructor Function (생성자 함수)

  • 과거 fucntion을 이용한 template에서 발전함
  • 계산하는 것 없이 순수하게 Objcect 생성하는 함수 만들때 사용
  • 이름 첫글자 대문자
function Person(name, age) {
    // this = {}; (원리가 생략 된 부분) interface(내장 함수)에서 제공
    this.name = name;
    this.age = age;
    // return this; (원리가 생략 된 부분)
}
const person5 = new Person('jerry', 34); // object 생성법
console.log(person5)



5. ‘in’ operator: property existence check (key in obj)

  • 해당하는 오브젝트안에 키가 있는지 없는지 확인하는 것
  • Boolean 형태로 return
console.log('name' in raccoon);
console.log('age' in raccoon);
console.log('random' in raccoon);
console.log(raccoon.random); // undefined



6. for..in vs for..of

  • for..in (key in obj) - object에만
    • object에서 key 한개씩 가져와 반복
for (const key in raccoon) {
    console.log(key);
}


  • for..of (value of iterable) - Array에만
    • Array에서 value 한개씩 가져와 반복
"for만 사용시"
const array = [1, 2, 4, 5];
for (let i = 0; i < array.length ; i++) {
    console.log(array[i]);
}

"of 사용시"
for (const value of array ) {
    console.log(value);
}



7. Fun cloning (복제)

  • cloning
    • object를 생성해서 다른 변수에 할당 (복제) -> 원래 그리고 다른 변수 모두 key, value가 연결되어 영향을 받음
const user = { name: 'ellie', age: '20'};
const user2 = user;
user2.name = 'coder'
console.log(user); // user의 name이 coder로 바뀜


  • 과거 object cloning way
const user3 = {}; // 복제할 곳 생성
for (const key in user) { // key 를 받아서 value를 모두 같게 함
    user3[key] = user[key];
}
console.log(user3);


  • Object.assign(destination, [obj1, obj2, obj3...])
    • Object.assign(Target, source1, source2, …)
    • source가 여러개면 앞에서 부터 순서대로 덮어쓰기 함
const user4 = {}; 
Object.assign(user4, user);
console.log(user4);

const user5 = Object.assign({}, user);
console.log(user5);

'Source가 여러개'
const fruit1 = { color: 'red' };
const fruit2 = { color: 'blue', size: 'big'};
const mixed = Object.assign({}, fruit1, fruit2);
console.log(mixed.color); 
console.log(mixed.size);





Array (list in python)

  • 값을 여러개 가지는 형태의 자료 구조



1. Declaration (선언)

  • new Array() , Array클래스를 new생성자로 생성
  • [] 를 사용하여 생성
const arr1 = new Array();
const arr2 = [1, 2];



2. Index position (인덱스)

  • 데이터 삽입, 삭제, 검색, 정렬을 어떻게 하는지가 중요함
  • index를 통해 가능
  • 첫번째 원소를 0으로 하여 시작함
const fruits = ['🍎', '🍌'];
console.log(fruits);
console.log(fruits.length); // 원소 개수
console.log(fruits[0]); // 사과
console.log(fruits[1]); // 바나나
console.log(fruits[fruits.length - 1]); // 배열의 마지막 숫자



3. Looping over an array (배열에서 반복)

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


  • for of
for (const fruit of fruits) {
    console.log(fruit);
}


  • forEach
  • forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
    • 해당 배열의 value, index, array를 param으로 받을수 있는데 그것을 활용해서 반복시킬수 있는 함수를 만들수 있음
fruits.forEach(function (fruit, index, array) {
    console.log(fruit, index, array);
}); // fruit 값 출력,  index는 인덱스 출력, array는 배열 자체 출력

fruits.forEach((fruit) => console.log(fruit));
// fruits배열의 fruit라는 이름의 매개변수인 value 형태를 가지고 원하는 함수를 구현



4. Addtion, deletion, copy (추가, 삭제, 복제)

  • push : add an item to the end (append in python)
fruits.push('🍓','🍑');
console.log(fruits);


  • pop : remove an item to the end and return a removed item (pop in python)
fruits.pop();
console.log(fruits);
fruits.pop();
console.log(fruits);


  • unshift : add an item to the begining
fruits.unshift('🍓','🍑');
console.log(fruits);


  • shift : remove an item to the begining
fruits.shift();
console.log(fruits);
fruits.shift();
console.log(fruits);
  • note!! shift, unshift are slower than pop, push. (shift, unshift는 위치를 모두 변경해 줘야해서 느림)


  • splice : remove an item by index position (not slice position)
    • parameter hint에 ? parm은 선택이라는 뜻(필수x)
    • splice(index start : number, deleteCount?: number) : string
fruits.push('🍓','🍑','🍋');
console.log(fruits);
fruits.splice(1, 1); // count number가 없으면 index num 부터 다 지움
console.log(fruits); 
fruits.splice(1, 1, '🍏','🍉'); // 지우고 그자리에 값 추가도 가능
console.log(fruits);


  • concat : combine two arrays (add end)
const fruits2 = ['🍐','🥥'];
const newFruits = fruits.concat(fruits2); // fruits 끝에 붙임
console.log(newFruits);



5. Searching (검색)

  • indexOf : find the index (앞에서 부터 찾음)
console.log(fruits);
console.log(fruits.indexOf('🍎')); // return index of specific value
console.log(fruits.indexOf('🍉'));
console.log(fruits.indexOf('🍄')); // 없을때 -1


  • lastIndexOf : find the index (끝에서 부터 찾음)
fruits.push('🍎') // 중복값을 가지는 경우
console.log(fruits);
console.log(fruits.indexOf('🍎')); // 0 (제일 첫번째로 만나는 값의 index return)
console.log(fruits.lastIndexOf('🍎')); // 5 (제일 마지막으로 만나는 값의 index return)


  • includes : check specific value in array -> boolean
console.log(fruits.includes('🍉')); // check specific value in array -> boolean
console.log(fruits.includes('🍄'));

숙제 : 정의된 부분들어가서 array api 확인하기

  • ctrl 누르고 해당 함수 클릭 -> 정의 된 곳으로 이동함