(JS) 객체, 배열, 생성자 함수, 계산된 프로퍼티, 객체 메서드

2023. 8. 12. 04:51
  • 객체
  • 접근할때 점이나 대괄호를 사용
    객체이름.객체키 // 객체값
    객체이름['객체키'] //객체값
  • 추가할때도 점이나 대괄호
    객체이름.추카키 = '추가값'
    객체이름['추가키'] = '추가값'
  • 삭제할땐 delete
    deltet 객체이름.객체키
  • 단축 프로퍼티 (키와 값이 일치할 경우에는 갑 생략 가능)
  • 프로퍼티 존재 여부 확인
    '존재확인하고싶은 키' in 객체이름 // false or true  

  • 배열

export default function App() {
let days = ['월', '화', '수'];
days.push('목'); // ['월', '화', '수', '목']
days.unshift('일'); ['일', '월', '화', '수', '목']
days.pop(); // ['일', '월', '화', '수']
days.shift(); // ['월', '화', '수']
days.splice(3, 0, '목', '금', '토', '일'); // ['월', '화', '수', '목', '금', '토', '일']

for (let i = 0; i < days.length; i++) {
console.log(days[i] + '요일');
}
// 월요일 ... 일요일

  • 붕어빵틀 생성자 함수 : 비슷한 객체 여러개를 만들 때 유용함
  function User(name, age) {
    this.name = name;
    this.age = age;
    this.sayName = function () {
      console.log(`내 이름은 ${this.name}`);
    };
  }

  // 생성자 함수 new
  let Mike = new User('Mike', 30);
  let Tom = new User('Tom', 27);

  console.log(Mike); // User {name: 'Mike', age: 30}
  console.log(Tom); // User {name: 'Tom', age: 27}

  // this=Tom
  Tom.sayName(); // 내 이름은 Tom

 

  • computed property(계산된 프로퍼티) :
    객체를 생성할 때 외부에 이미 선언해둔 변수 이름을 [key]로 가져와서 사용할 수 있음. 수식도 사용할 수 있다.
 
  let 나이 = 'age';
  const user = {
    name: '다람이',
    [나이]: 7,
  };

  console.log(user); // {name: '다람이', age: 7}

  let age = '나이';
  let name = '이름';

  const example = {
    [name + '']: '다람이',
    [age + '']: '7살',
  };
  console.log(example); // {이름은: '다람이', 나이는: '7살'}
 

 

  • 객체 메서드 : 
  • Object.assign() : 객체 복제
  const user = {
    name: '다람이',
    age: 7,
  };

  const newUser = Object.assign({ color: 'orange', age: 8 }, user);
  console.log('user', user);
  console.log('newUser', newUser);
  /* {color: 'orange', age: 7, name: '다람이'} 가 나온다.
  복제본에 병합하지만 원본과 key가 겹칠 경우에는 원본이 덮어씌우기 되는 셈.  */
  • Object.values() : 객체의 값만 반환 
  const newUserValue = Object.values(newUser);
  console.log(newUserValue); //  ['orange', 7, '다람이']
  • Object.keys() : 객체의 키만 반환
  const newUserKey = Object.keys(newUser);
  console.log(newUserKey); //['color', 'age', 'name']
  • Object.entries() : 객체의 키와 값을 배열로 반환
  const newUserEntries = Object.entries(newUser);
  console.log(newUserEntries);
  /* [
    ['color', 'orange']
    ['age', 7]
    ['name', '다람이']
    ] */
  • Object.fromEntries : 배열을 객체로 반환
  const newUserFromEntries = Object.fromEntries(newUserEntries);
  console.log('newUserFromEntries', newUserFromEntries);
//{color: 'orange', age: 7, name: '다람이'}




출처 : https://www.youtube.com/@codingangma