0. Literals and properties
one of the JS 's data types
a collection of related data and/or functionality.
Nearly all objects in JS are instances of object
object = { key : value };
const obj1 = {}; // 'object literal' syntax
const obj2 = new Object(); // 'object constructor' syntax
function print(person){
console.log(person.name);
console.log(person.age);
}
const cucu = { name : 'cucu', age : '10'};
print(cucu);
cucu.hasJob = true; //동적 코딩 가능 -> 유지,보수 힘듦.
console.log(cucu.hasJob);
1. Computed properties
console.log(cucu.name);
console.log(cucu['name']); // key is string type!!
cucu['hasJob']=false;
console.log(cucu['hasJob']);
//실시간으로 원하는 key 받고 싶다면
function printValue(obj, key){
console.log(obj[key]);
}
printValue(cucu, 'name');
2. Property value shorthand
//일일이 만들면 반복하게 됨.
const perosn1 = {name: 'bab', age: 3};
const perosn2 = {name: 'aba', age: 2};
const perosn3 = {name: 'cuc', age: 1};
const person4 = new Person('cucu', 20);
console.log(person4);
function Person(name, age){
// this = {};
this.name = name;
this.age = age;
// return this;
}
3. In operator : property existence check
해당하는 key 가 object 에 있는지 확인 가능
console.log('name' in cucu);
4. ★ for..in vs for..of
console.clear();
for (key in cucu){
console.log(key);
}
const array = [1, 2, 3, 5];
for (value of array) {
console.log(value);
}
5. Cloning
const user = { name : "cucu", age : "9"};
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
const user4 = Object.assign({}, user);
console.log(user4);
const fruit1 = {color : "red"};
const fruit2 = {color : "blue", size : "small"};
const mixed = Object.assign({}, fruit1, fruit2); // 제일 뒤에 있는게 계속 덮어씌움
console.log(mixed.color);
console.log(mixed.size);
'Programming > JavaScript' 카테고리의 다른 글
flex-shrink, flex-wrap, justify-content (0) | 2024.03.14 |
---|---|
JS 문법 정리 (6) (0) | 2023.08.24 |
JS 문법 정리 (4) (0) | 2023.08.18 |
JS 문법 정리 (3) (1) | 2023.08.15 |
JS 문법 정리 (2) (0) | 2023.08.15 |