【ES6系列】Destructure 解构赋值

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

思考:

  1. 有时候我们写一个函数需要传入很多参数,而且很多参数是可选的,是否可以利用解构赋值来简化操作呢?
  2. 如何在业务开发中对接口数据进行解构赋值?

你可能感兴趣的:(ES6,Javascript,基本功)