深入理解ES6之《解构》

发布时间:2019-06-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了深入理解ES6之《解构》脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

对象解构

如果使用VARletconst解析声明变量,则必须提供初始化程序(也就是等号右侧的值)
以下语句有语法错误

var { tyPE, name };
let { type, name }
const { type, name }

解构赋值表达式(也就是右侧的表达式)如果为null或undefined会导致程序抛出错误,因为任何尝试读取null或undefined的属性的行为都会触发运行时错误

let node = {
  type: 'Identifier',
  name: 'angela'
}
let { type, name } = node

上面代码是声明type、name变量同时赋值node相应的属性值
那如果已经存在type、name,重新赋值 使用解构的话则需要在表达式两侧加小括号

let node = {
  type: 'Identifier',
  name: 'angela'
},
  type = 'demo',
  name = 1;
//添加小括号可以将块语句转化为一个表达式,从而实现整个解构赋值的过程
({ type, name } = node)

在任何使用值的地方你都可以使用解构赋值表达式

let node = {
  type: 'Identifier',
  name: 'angela'
},
  type = 'demo',
  name = 1;
function outputInfo(value) {
  console.LOG(value === node)
}
outputInfo({ type, name } = node)//true

解构还可以使用默认值

let node = {
  type: 'Identifier',
  name: 'angela'
}
let { type, name, value = true } = node

为非同名局部变量赋值

let node = {
  type: 'Identifier'
}
let { type: localType, name: localName = "angela" } = node
console.log(localType)//Identifier
console.log(localName)//angela

解构嵌套对象,很可能会无意中创建一个无效表达式,比方说下面的loc后的大括号则不需要,更好的做法是定义一个默认值

let { loc: { } } = node

数组解构

let colors = ['red', 'green', 'blue']
let [, , thirdColor] = colors

可以像如上所示只取数组第三个元素,忽略前两个

let colors = ['red', 'green', 'blue'],
  FirstColor = 'black',
  secondColor = 'purple';
[firstColor, secondColor] = colors

对变量重新赋值利用解构时,数组解构不再需要左右两侧加小括号了
可能数组解构用的最多的莫过于交换值吧

let a = 1,
  b = 2;
[a, b] = [b, a]

同样数组解构中也可以添加默认值
数组解构中有一个不定元素的概念,可以通过...语法将数组中的其余元素赋值给一个特定的变量

let colors = ['red', 'green', 'blue'];
let [firstColor, ...restColors] = colors//restColors包含两个元素green和blue

concat方法的设计初衷是连接两个数组,如果调用时不传递参数就会返回当前函数的副本

let colors = ['red', 'green', 'blue'];
let cloneColors = colors.concat() //["red", "green", "blue"]

上述代码用ES6中不定元素也可以实现该目标

let colors = ['red', 'green', 'blue'];
let [...cloneColors] = colors //["red", "green", "blue"]

需要注意的是在被解构的数组中,不定元素必须为最后一个条目,在后面继续添加逗号会导致语法错误
解构参数

function setCookie(name, value, { secure, path, domain, expires }={}) {

}
setCookie("type", "js", { secure: true, expires: 6000 })

想的最全面的就是既使用解构又使用默认值

const setCookiedefaults = {
  secure: false,
  path: "/",
  domain: "example.COM",
  expires: new Date(Date.now() + 360000000)

}
function setCookie(name, value,
  { secure = setCookieDefaults.secure,
    path = setCookieDefaults.path,
    domain = setCookieDefaults.domain,
    expires = setCookieDefaults.expires }) {
}

脚本宝典总结

以上是脚本宝典为你收集整理的深入理解ES6之《解构》全部内容,希望文章能够帮你解决深入理解ES6之《解构》所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。