"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > JavaScript - 배열 및 객체 구조 분해 [Live Doc]

JavaScript - 배열 및 객체 구조 분해 [Live Doc]

2024-08-26에 게시됨
검색:273

JavaScript - Destructuring Arrays & Objects [Live Doc]

  • 새로운 주제를 따로 공부하세요. 그렇지 않으면 장기적으로 개념을 완전히 이해할 수 없습니다. 이는 일부 경험적 연구에서도 뒷받침됩니다.
  • 구조 분해: 배열이나 객체의 값을 별도의 변수로 압축 해제하는 방법입니다.
const nums = [8,4,5];
const num1 = nums[0];
const num2 = nums[1];
const num3 = nums[2];
console.log(num1, num2, num3);

is reduced to 

const [x,y,z] = nums;
console.log(x, y, z);

three const variables named x,y,z are created in this step
  • [x,y,z] 배열처럼 보이지만 =의 LHS에 있으면 구조 분해로 간주됩니다.
  • 구조 분해는 불변 작업입니다.
const girl = {
  name: 'Melania',
  friends: ['Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya'],
  eats: ['Roasted', 'Pizza', 'Burger', 'Rice', 'Manchurian'],
};

const [first, second] = girl.friends;
console.log(first, second);

const [,,,fourth,last] = girl.eats;
console.log(fourth, last);

변수 교환 [돌연변이]

let array = [5,6];
let [a,b] = array;
console.log(`a: ${a}, b:${b}`);
[b,a] = [a,b];
console.log(`a: ${a}, b:${b}`);

함수는 배열을 반환하고 결과를 즉시 파괴하여 함수에서 여러 값을 반환할 수 있습니다.

const girl = {
  name: 'Melania',
  friends: ['Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya'],
  eats: ['Roasted', 'Pizza', 'Burger', 'Rice', 'Manchurian'],
  drinks: ['Juice','Coffee','Coke'],
  order: function(eat,drink){
    return [this.eats[eat],this.drinks[drink]];
  }
};

const [mainCourse, drinks] = girl.order(2, 2);

console.log(`mainCOurse: ${mainCourse}`);
console.log(`drinks: ${drinks}`);

중첩 배열 구조 분해

let nums = [5,3,[8,7,9,3]];
let [x,y,z] = nums;
console.log(`x: ${x}`); // 5
console.log(`y: ${y}`); // 3
console.log(`z: ${z}`); // 8,7,9,3

let nums2 = [5,3,[8,7]];
let [x,,[y,z]] = nums2;
console.log(`x: ${x}`, `y: ${y}`, `z: ${z}`); // 5 8 7 

알 수 없는 크기의 배열에서 구조 분해:

const names = ['Michael','Charlie','Peter'];
let [w='XXX',x='XXX',y='XXX',z='XXX'] = names;
console.log(w,x,y,z); // 'Michael' 'Charlie' 'Peter' 'XXX'

객체 파괴:

  • 객체 구조 분해에는 {}를 사용하고 배열 분해에는 []를 사용합니다.
  • 추출할 객체의 속성 이름에 언급된 정확한 변수 이름을 제공하십시오. 이러한 변수 이름의 순서는 중요하지 않습니다.
const girl = {
  name: 'Melania',
  friends: ['Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya'],
  eats: ['Roasted', 'Pizza', 'Burger', 'Rice', 'Manchurian'],
  drinks: ['Juice','Coffee','Coke'],
  works: {
        mtwt: {
          start: 9,
          end: 5
        },
        fri: {
          start:9,
          end: 3
        }
  }
};

const {name, works, drinks} = girl;
console.log(name);
console.log(works);
console.log(drinks);


// Replace long property names with custom names:
const {name:user, works:timings, drinks:enjoys} = girl;
console.log(user);
console.log(timings);
console.log(enjoys);


//Destructuring data from API calls returned in the form of objects i.e Attaching a default value to a property that does not exist on object received from an API call

// details does not exist, so default value is assigned
const { details = [], eats: loves = [] } = girl;
console.log(details);
// eats exist but is renamed as loves, hence default value won't apply
console.log(loves);
## Mutating Variables using object destructuring
let x = 10;
let y = 20;
let obj = {x:1, y:2, z:3};

{x,y} = obj; // Error
When we start a line with a '{', then JS expects a code-block. And we cannot assign anything to a code-block on LHS using = operator. Hence, an Error is thrown. The error is resolved by wrapping into () as shown below
({x,y} = obj); //{ x: 1, y: 2, z: 3 }

중첩된 객체 구조 분해

const girl = {
  name: 'Melania',
  friends: ['Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya'],
  eats: ['Roasted', 'Pizza', 'Burger', 'Rice', 'Manchurian'],
  drinks: ['Juice','Coffee','Coke'],
  works: {
        mtwt: {
          start: 9,
          end: 5
        },
        fri: {
          start:10,
          end: 2
        }
  }
};

let { fri } = works;
console.log(fri);

// Destructuring the fri object using the same property names start, end
let {fri: {start, end}} = works;
console.log(start, end);

// Further renaming for shortening start as 'b' and end as 'e'
let {fri: {start: b, end: e}} = works;
console.log(b, e);





const girl = {
  name: 'Melania',
  friends: ['Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya'],
  eats: ['Roasted', 'Pizza', 'Burger', 'Rice', 'Manchurian'],
  drinks: ['Juice','Coffee','Coke'],
  works: {
        mtwt: {
          start: 9,
          end: 5
        },
        fri: {
          start:10,
          end: 2
        }
  },
  // these destructured property-names have to be same as they are passed inside the girl.sleep(). Order need not be same.
  sleep: function ({time='NA', address='NA', color = 'NA', duration='NA'}){
    console.log(`${this.name} sleeps at ${address} for ${duration} in ${color}light for ${duration}. She loves to eat ${this.eats[0]}`);
  }
};

// A single object is passed, which will be destructured by the method inside the object extracting all values via destructuring
girl.sleep({time: '10pm', address:'home', color: 'blue', duration: '7hrs'});

girl.sleep({time: '9pm', duration: '7hrs'});
릴리스 선언문 이 기사는 https://dev.to/mahf001/javascript-destructuring-arrays-objects-1agk?1에서 복제됩니다.1 침해 내용이 있는 경우, [email protected]으로 연락하여 삭제하시기 바랍니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3