[ES6]解构赋值

在ES6中新增了变量赋值的方式。

数组解构赋值

按照一定的模式,从数组和对象中提取值。

let [a, b, c] = [1, 2, 3]

解构赋值的重点在于和左侧要和右侧有类似的格式,例如上面的中括号[ ]

赋值元素可以是任意可遍历元素

let [a, b, c] = "abc" // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3])

可以跳过赋值元素

如果想跳过数组的某个元素进行赋值,可以使用逗号实现。

let [name, , title] = ['John', 'Jim', 'Sun', 'Moon']

console.log( title ) // Sun

使用rest获取剩下的数组元素

let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"]

console.log(name1) // Julius
console.log(name2) // Caesar

// Note that type of `rest` is Array.
console.log(rest[0]) // Consul
console.log(rest[1]) // of the Roman Republic
console.log(rest.length) // 2

注意:要保证rest放在最后的位置。

默认值

如果对应位置没有值,则取默认值。

let [name = "Guest", surname = "Anonymous"] = ["Julius"]

console.log(name)    // Julius (from array)
console.log(surname) // Anonymous (default used)

对象解构赋值

同样我们在=左侧要有和右侧类似的格式。

let options = {
  title: "Menu",
  width: 100,
  height: 200
}

let {title, width, height} = options

console.log(title)  // Menu
console.log(width)  // 100
console.log(height) // 200

注:属性的顺序无需一致。

改变获取属性名

对象的属性名: 自定义变量名

let {width: w, height: h, title} = options

注:当我们自定义变量名后,默认的变量名将不可用。

默认值

对应位置没有值时,取默认值。

let options = {
  title: "Menu"
}

let {width = 100, height = 200, title} = options

console.log(title)  // Menu
console.log(width)  // 100
console.log(height) // 200

rest运算符

存储剩余属性,rest为对象。

let options = {
  title: "Menu",
  height: 200,
  width: 100
}

let {title, ...rest} = options

// now title="Menu", rest={height: 200, width: 100}
console.log(rest.height)  // 200
console.log(rest.width)   // 100

嵌套对象

如果一个Array或者Object比较复杂,嵌套了很多层,那么和之前一样,在=左边与右边的结构一致即可。

let options = {
  size: {
    width: 100,
    height: 200
  },
  items: ["Cake", "Donut"],
  extra: true    // something extra that we will not destruct
}

// destructuring assignment on multiple lines for clarity
let {
  size: { // put size here
    width,
    height
  },
  items: [item1, item2], // assign items here
  title = 'Menu' // not present in the object (default value is used)
} = options

console.log(title)  // Menu
console.log(width)  // 100
console.log(height) // 200
console.log(item1)  // Cake
console.log(item2)  // Donut

注意:此处的size和items仅为结构,不是变量。若要保存对应的size,可以这样。

let {
  size},
  items: [item1, item2],
  title = 'Menu'
} = options

你可能感兴趣的:([ES6]解构赋值)