ES5 從一個複雜的數據結構中提取數據是如何實現的?ES6 有更優雅便捷的方式嗎?
ES6之解構賦值。解構賦值重點是在賦值,賦值的元素是要拷貝出來賦值給變量,賦值的元素本身是不會被改變的。
// let arr = ['hello', 'world']
// let [firstName, surName] = arr
// console.log(firstName, surName)
一、數組解構賦值 Array Destructuring
// 如果想忽略數組的某個元素對變量進行賦值,可以使用逗號來處理。
let arr = ['a', 'b', 'c', 'd']
let [firstName, , thirdName] = arr
console.log(firstName, thirdName) // a c
//賦值元素可以是任意可遍歷的對象
let [firstName, , thirdName] = new Set(['Alice', 'Amy', 'Feiby'])
console.log(firstName, thirdName) //Alice Feiby
//被賦值的變量還可以是對象的屬性,不侷限於單純的變量。
let obj = {};
[obj.name, obj.usrname] = 'John Z'.split(' ');
console.log(obj.name) // John
console.log(obj.usrname) // Z
// 解構賦值在循環體中的應用
let user = {
name: 's',
surName: 't'
}
// Object.entries 把傳入的對象轉換成一個可遍歷的對象
for (let [key, value] of Object.entries(user)) {
console.log(key, value) // name s // surName t
}
// rest 變量
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let [firstName, curName, ...last] = arr
console.log(firstName, curName, last) // 1 2 (7) [3, 4, 5, 6, 7, 8, 9]
// 如果數組的內容少於變量的個數,並不會報錯,沒有分配到內容的變量會是 undefined。
//你也可以給變量賦予默認值,防止 undefined 的情況出現:
let [name = "Guest", surname = "Anonymous"] = ["Julius"];
console.log(name); // Julius (from array)
console.log(surname); // Anonymous (default used)
二、Object 解構賦值 Object Destructuring
let options = {
title: 'menu',
width: 100,
height: 200
}
// 簡寫形式,變量名必須和對象的key一致
let {
title,
width,
height
} = options
console.log(title, width, height)
// 非簡寫形式
let {
title: newTitle
} = options
console.log(newTitle)
// 指定默認值
let options = {
// title: 'menu',
// width: 100,
height: 200
}
let {
title = 'list',
width = 130
} = options
console.log(title, width)
// rest 變量
let options = {
title: 'menu',
width: 100,
height: 200
}
let {
title = 'list', ...last
} = options
console.log(title, last) //menu {width: 100, height: 200}
// 複雜數據結構的解構賦值。解構原理:左右數據結構保持嚴格的一致
let others = {
size: {
width: 100,
height: 200
},
items: ['cake', 'donut'],
extra: true
}
let {
size: {
width,
height
},
items: [, item2],
extra
} = others // 左右數據結構要保持一致
console.log(width, height, item2, extra) //100 200 "donut" true
思考:
- 有時候我們寫一個函數需要傳入很多參數,而且很多參數是可選的,是否可以利用解構賦值來簡化操作呢?
- 如何在業務開發中對接口數據進行解構賦值?