JavaScript 기초 문법

JavaScript 문법 - 객체 (Object)

신나몬롤 2022. 10. 9. 18:28

Object (오브젝트)

- One of the JavaScript's data types.

- A collection of related data and/or functionality
- Nearly all objects in JS are instances of Object
- Object = { key : value }  : 오브젝트는 우리가 접근할 수 있는 변수/속성과 그 속성이 가지고 있는 값
 두 가지로 나눠지는데, { key : value } 의 형태이다. ex) { name : ‘Diana’ }

 

const name = 'Diana';
const age = 4;
print(name, age);
function print(name, age) {
  console.log(name);
  console.log(age);
}

이렇게 작성할 경우, 주소나 다른 Diana의 정보 같은 인자가 많아지게 되면 추가해야되는게 많아지기 때문에 관리도 힘들고 그룹으로 묶어서 생각할 수도 없다.

 

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

const Diana = { name : 'Diana', age : 20 };
print(Diana);

따라서, 이렇게 persone 이라는 데이터를 받아서 person.name & person.age를 출력할 수 있다.

호출할 때도 Diana만 전달하면 되기 때문에 간편하게 데이터를 관리할 수 있다.

 


오브젝트를 만드는 방법

const obj1 = {}; // 'object literal' syntax
const obj2 = new Object(); // 'object constructor' syntax

* 오브젝트를 new라는 키워드를 이용해 생성하면, 오브젝트에서 정의된 constructor 가 호출되어 이름이 지어진 것

 


computed properties ; 계산된 속성

- key should be always string

console.log(Diana.name); //(1)
console.log(Diana['name']); //(2)

둘다 output 은 Diana

(1) 우리가 오브젝트 안에 있는 데이터에 접근할 때는 dot(점)을 이용한다.

(2) Diana라는 오브젝트에 괄호를 이용해서 name이라는 string 즉, 오브젝트 안에 있는 변수의 이름을 string 형태로 접근이 가능하다. * 이 때, property는 string 타입이어야 한다.

console.log(Diana[name]); // undefined

 


in operator ; property existence check

key in obj 

function person(name, age) {
  return {
    name: name, // name: 생략 가능
    age: age, // age: 생략 가능
    hobby: "golf" // 
  };
}
 
const Diana = person("Diana", 20);
console.log(Diana); // { name: 'Diana', age: 20, hobby: 'golf' }

console.log("age" in Diana); // true
console.log("birthday" in Diana); // false
console.log(Diana.random); // undefined

* 하지만, 이 예시는 dot이나 대괄호로도 확인이 가능해서 실용적인 예시는 아님

 

function isAdult(user) {
  if (!('age' in user) || // user에 age가 없거나
      user.age < 20) { // 20살 미만이거나
    return false;
  }
  return true;
}

const Diana = {
  name: "Diana",
  age: 20 
};

const Chris = {
  name: "Chris"
};

console.log(isAdult(Chris))

 


of opertor

key of obj

 

const array = [1, 3, 4, 8];
for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}
// output : 1, 3, 4, 8

const array = [1, 3, 4, 8];
for (value of array) {
  console.log(value);
}
// output : 1, 3, 4, 8

위의 for 문으로 1,3,4,8을 출력한 것 처럼 key of obj 로도 출력이 가능하다.