深入理解ES6--解构

版权声明:本文为博主原创文章,未经博主允许不得转载。转载请标明出处:http://blog.csdn.net/ligang2585116! https://blog.csdn.net/ligang2585116/article/details/79750367

解构时一种打破数据结构,将其拆分为更小部分的过程。解构在实际开发中经常会应用到对象和数组中。关于解构的基本用法,请参考:ES6–变量的声明及解构赋值

解构:使数据访问更便捷

对象解构

  • 解构赋值
    一定要用一对小括号包裹解构赋值语句,javascript引擎将一对开放的花括号视为一个代码块,而语法规定,代码块语句不允许出现在赋值语句左侧,添加小括号后可以将块语句转化为一个表达式,从而实现整个解构赋值的过程。
const node = {a: 1, b: 2};
let {a, b} = node;

// 对已经声明的变量赋值
const node = {a: 1, b: 2};
let a, b;
({a, b} = node)
  • 深层解构
const obj = {a: {b: 1}};
let {a: {b}} = obj;
console.log(a)  // a is not defined
console.log(b)  // 1
  • 默认值
    如果指定的局部变量名称在对象中不存在,那么这个局部变量会被赋值为undefined。
const node = {a: 1, b: 2};
let {a, b, c} = node;
// 可以使用默认值
let {a, b, c = 3} = node;

注意: 如果值为null,不会执行默认值,只有为undefined才会走默认值

const node = {a:1, b: 2, c: null, d: undefined};
let {a, b, c = 3, d = 4} = node;
console.log(c, d); // null 4
  • 为非同名局部变量赋值
const node = {a:1, b: 2};
let {a: A, b: B} = node;
console.log(A, B); // 1 2

所有冒号前的标识符都代表在对象中的检索位置,其右侧为被赋值的变量名。

示例:将一个对象的部分属性赋值给另外一个对象

let obj1 = {a: 1, b: 1}
let obj2 = {a: 2, b: 2}
({a: obj2.a} = obj1) // Invalid destructuring assignment target
  • 不定元素解构
let obj = {a: 1, b: 2}
let {a, ...obj2} = obj
console.log(a, obj2) // 1 {b: 2}

特别说明:
ES6中展开运算符只针对iterable才起作用,默认有数组、set、map和字符串。并不包含对象!ES6规范中也并未将展开运算符支持对象,但是目前的主流浏览器Chrome和firefox均已实现该特性。这意味着如果想在低版本浏览器中使用需要特别的Babel插件进行转换!object-rest-spread
object-rest-spread

数组解构

通过在数组中的位置进行选取,且可以将其存储在任意变量中,未“显式声明”的元素都会被直接被忽略。

let colors = ['red', 'blue', 'green'];
let [, , thirdColor] = colors;
console.log(thirdColor)

// 对已声明的变量进行赋值
let colors = ['red', 'blue', 'green'];
let thirdColor;
[, , thirdColor] = colors;

注意:不需要小括号包裹表达式,这一点与对象解构的约定不同

不定元素

let colors = ['red', 'blue', 'green'];
let [firstColor, ...otherColor] = colors;
console.log(otherColor) // ["blue", "green"]

...语法将数组中的其余元素赋值给一个待定的变量。

示例:克隆数组

let colors = ['red', 'blue', 'green'];
// es5方式
colors.concat()
// es6方式
[...colors]

注意:在被解构的数组中,不定元素必须为最后一个条目!

解构参数

function test(a, {b, c}) {
  console.log(a, b, c)
}
test(1, {b: 2, c: 3})   // 1 2 3
test(4) // Uncaught TypeError: Cannot destructure property `b` of 'undefined' or 'null'.

注意:解构参数,调用函数不提供被解构的参数会导致程序抛出错误。let {b, c} = undefined;

扫描二维码关注公众号,回复: 3168611 查看本文章

处理方式,让上述参数可选!

function test(a, {b, c} = {}) {
  console.log(a, b, c)
}
test(1, {b: 2, c: 3})   // 1 2 3
test(4) // 4 undefined undefined

猜你喜欢

转载自blog.csdn.net/ligang2585116/article/details/79750367