02.ES6对象解构

2020-06-02  本文已影响0人  __豆约翰__

对象解构

const note = {
  id: 1,
  title: 'My first note',
  date: '01/01/1970',
}
// Destructure properties into variables
const { id, title, date } = note

等价于以下代码:

// Create variables from the Object properties
const id = note.id
const title = note.title
const date = note.date
console.log(id)
console.log(title)
console.log(date)

起个别名

// Assign a custom name to a destructured value
const { id: noteId, title, date } = note
console.log(noteId)

复合对象

const note = {
  id: 1,
  title: 'My first note',
  date: '01/01/1970',
  author: {
    firstName: 'Sherlock',
    lastName: 'Holmes',
  },
}
// Destructure nested properties
const {
  id,
  title,
  date,
  author: { firstName, lastName },
} = note
console.log(`${firstName} ${lastName}`)

上面代码不可以访问author对象,需要下面这么做:

// Access object and nested values
const {
  author,
  author: { firstName, lastName },
} = note

console.log(author)

还可以这样

const { length } = 'A string'
console.log(length)
8

数组解构

const date = ['1970', '12', '01']
// Create variables from the Array items
const year = date[0]
const month = date[1]
const day = date[2]

console.log(year)
console.log(month)
console.log(day)
const date = ['1970', '12', '01']

// Destructure Array values into variables
const [year, month, day] = date

console.log(year)
console.log(month)
console.log(day)
// Skip the second item in the array
const [year, , day] = date

console.log(year)
console.log(day)

嵌套数组

// Create a nested array
const nestedArray = [1, 2, [3, 4], 5]
// Destructure nested items
const [one, two, [three, four], five] = nestedArray

console.log(one, two, three, four, five)

复杂对象析构,并添加变量

const note = {
  title: 'My first note',
  author: {
    firstName: 'Sherlock',
    lastName: 'Holmes',
  },
  tags: ['personal', 'writing', 'investigations'],
}
const {
  title,
  date = new Date(),
  author: { firstName },
  tags: [personalTag, writingTag],
} = note

console.log(date)
console.log(firstName)
console.log(writingTag)

上一篇 下一篇

猜你喜欢

热点阅读