iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

30 天線上自學前端系列 第 62

[Day 62] [React] ES6 Object & Array Destructuring

  • 分享至 

  • xImage
  •  

前幾天有看到老師第一次提到 Destructuring 是在這一天 [Day 60] [React] State - Hooks - useState & destructuring assignment 解構賦值,當時老師沒有提及太多,所以自己去查了一點資料。

今天除了會複習之前稍微提到的 Destructuring assignment、object、array 以外,也會更深入的介紹 destructuring。

  • Destructure Array
  • Destructure Object
  • Default Value
  • Nested Object

老師給的 codesandbox 裡面,有一個檔案 data.js 放了一個 array,裡面有兩個 items:

const animals = [
  { name: "cat", sound: "meow" },
  { name: "dog", sound: "woof" }
];

下一步是到 index.js,import 這個檔案然後 console.log 看有得到什麼資料:

https://ithelp.ithome.com.tw/upload/images/20221112/2015158856pkJkbopo.png


Destructure Array

把 item 從 array 裡面解放出來變成變數

我們第一件事是可以把這個動物 array destructure 變成變數,這樣就可以保留第一個 item "cat" 和第二個 item "dog"。

const [cat, dog]=animals;

cat & dog 只是取個名字,主要是看順序,所以也可以換句話說:

const [cat, dog]=animals;
/* 換句話說:
const catCat = animals[0];

另外是在 destructure 時,變數名稱必須是整個文件裡唯一的,這也是為什麼我上面第二個變數名稱是 catCat,不然他不給我 console.log QQ。


Destructure Object

把 item 從 array 裡面解放出來變成變數後,接著解構 object。

https://ithelp.ithome.com.tw/upload/images/20221112/2015158856pkJkbopo.png

我們目前知道 Cat object 裡面有兩個 properties,name & sound。

跟前面一樣我們可以用 {} 來創造兩個變數,分別裝 name & sound 的 properties。

const {name , sound} = cat;

/* 這邊名字不可替換,要跟 key 一樣的名字,不然會不知道要提取個資料。

console.log(name)
console.log(sound)

/* 以上跟下面的意思是一樣的
console.log(cat.name)
console.log(cat.sound)

這樣可以讓 code 看起來更簡潔跟易讀,比如以下的例子也是可以叫出 meow,但會比較不方便看:

animals[0].sound

我們也可以把 cat & meow 變成變數:

const {name: catName , sound: catSound} = cat;

Default Value

預設值是當回傳的 property 是空的時,就會先遞補上預設值。

const {name: "fluffy" , sound: "purr"} = cat;

加上引號就可以把內容變為預設值。


Nested Object

一個 object 裡面還有另一個 object。

https://ithelp.ithome.com.tw/upload/images/20221112/201515885qznp4tDjf.png

const animals = [
  { name: "cat", 
    sound: "meow", 
    feedingRequirement: {
        food: 2,
        water: 3
      }
  },
  { name: "dog", sound: "woof" }
];

如果想要知道 food 裡面的值可以這樣做:

const {name, sound, feedingRequirement: {food, water} } = cat;

console.log(food);     //2

上一篇
[Day 61] [React] State - Hooks - useState Hook 練習
下一篇
[Day 63] [React] ES6 Object & Array Destructuring 練習
系列文
30 天線上自學前端72
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言