首頁 > web前端 > js教程 > JavaScript - 解構陣列和物件 [即時文件]

JavaScript - 解構陣列和物件 [即時文件]

王林
發布: 2024-08-19 20:30:54
原創
636 人瀏覽過

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'});
登入後複製

以上是JavaScript - 解構陣列和物件 [即時文件]的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板