美文网首页
02.ES6对象解构

02.ES6对象解构

作者: __豆约翰__ | 来源:发表于2020-06-02 15:16 被阅读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)

相关文章

  • 02.ES6对象解构

    对象解构 等价于以下代码: 起个别名 复合对象 上面代码不可以访问author对象,需要下面这么做: 还可以这样 ...

  • 3.解构赋值

    解构的分类 对象解构 数组解构 混合解构 解构参数 对象解构 解构赋值 嵌套对象解构 数组解构 数组解构 选择性的...

  • 深入理解ES6--5.解构:更方便的数据访问

    主要知识点:对象解构、数组解构、混合解构以及参数解构 1. 对象解构 对象解构语法 对象解构语法在赋值语句的左侧使...

  • ES6系列 (六)解构

    目标 解构对象 解构数组 结合数组解构和对象解构 了解解构的类型 思考 解构对象 使用解构语句解构数据结构,提取n...

  • 解构赋值

    解构赋值 数组的解构赋值 嵌套,默认值,展开符 对象的解构赋值 对象解构赋值的本质与简写 对象解构的模式与变量 对...

  • ES6之解构表达式

    数组解构 对象解构

  • ES6之解构

    对象解构 解构赋值 默认值 数组解构 数组解构的语法看起来与对象解构非常相似,只是将对象字面量替换成了数组字面量。...

  • ECMAScript6 -- 解构赋值

    解构赋值 数组的解构赋值 对象的解构赋值 特殊: 数组的解构赋值 如果右边不是数组,默认转换为类数组 对象的解构赋...

  • 变量的解构总结

    es变量赋值的新写法 不完全解构、 报错的几种情况: 默认值 对象解构,对象解构没有秩序 字符串解构 函数解构 用...

  • ES6-对象解构与数组解构

    1.对象解构 2.数组解构

网友评论

      本文标题:02.ES6对象解构

      本文链接:https://www.haomeiwen.com/subject/afbuzhtx.html