[JS]解構賦值

IE 最新版瀏覽器 IE11 還不支援 Destructuring。

JavaScript ES6 Array and Object Destructuring Assignment 陣列和物件的解構賦值

解構賦值 (Destructuring Assignment)是一個在 ES6 的新特性,目的用於提取陣列或物件中的資料變成獨立變數。

物件解構賦值的基本使用方法如下:

let obj = { website: "pjchender", country: "Taiwan" } let {website, country} = obj; console.log(website); // pjchender console.log(country); // Taiwan

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

圖片來源: PJChender 部落格

所以真正被建立和賦值的 let{ } 當中,冒號(:)後的變數。

let obj = { website: "pjchender", country: "Taiwan" } let {website:wb, country:ct} = obj; console.log(website, country); // Error:website in not defined console.log(wb, ct) // "pjchender", "Taiwan"

物件解構賦值的用途相當多(可參考阮一峰-ECMAScript 6 入門),其中在提取 JSON 數據時相當方便:

let data_JSON = { id: 74, website: "pjchender", country: "Taiwan", detail:{ add: "Tainan", phone: "0933333333" } } let {id, website, country, detail} = data_JSON; console.log(id, website, country, detail);