前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ES6之解构赋值

ES6之解构赋值

作者头像
19组清风
发布2021-11-15 15:05:30
1740
发布2021-11-15 15:05:30
举报
文章被收录于专栏:Web Front EndWeb Front End
  1. 赋值元素可以是任意可遍历的对象
    1. 被赋值的变量还可以是对象的属性,不局限于单纯的变量。
    2. 循环体。
    3. 跳过赋值元素。(使用逗号)
    4. rest参数。(剩余数组 or 剩余Object,放在最后一位)。
    5. 默认值。
    6. 重命名。(对于Object的解构)
    7. 字符串也可以解构。(Array形式接受)
代码语言:javascript
复制
// 任意可迭代对象都可以赋值
let [a, b, c] = "abc" // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3])
//  被赋值的变量还可以是对象的属性,不局限于单纯的变量。
const user = {};
[user.firstName, user.secondName] = 'Kobe Bryant'.split(' ')

console.log(user.firstName, user.secondName) // Kobe Bryant

// 循环体
let user = {
    name: 'John',
    age: 30
}

// loop over keys-and-values
for (let [key, value] of Object.entries(user)) {
    console.log(`${key}:${value}`) // name:John, then age:30
}

// 可以跳过赋值元素
// 如果想忽略数组的某个元素对变量进行赋值,可以使用逗号来处理。
// second element is not needed
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

// 默认值
// default values
let [name = "Guest", surname = "Anonymous"] = ["Julius"]

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

// 重命名
let {width: w, height: h, title} = options

// 字符串也可以解构
let str = 'imooc'

let [a, b, c, d, e] = str

console.log(a, b, c, d, e)
复制代码
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020年09月08日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档