ES6解构

作用

拆分数据解构,更方便的提取数据片段。

对象解构

声明变量

使用解构声明变量必须初始化
ES5

const obj = {
    name: 'lee',
    age: 18
}
let name = obj.name;
let age = obj.age;

ES6

const obj = {
    name: 'lee',
    age: 18
}
let { name, age } = obj;

赋值变量

const obj = {
    name: 'lee',
    age: 18
}
let name = 'hello';
let age = 7;
({ name, age } = obj);

默认值

如果指定的变量名称在对象中不存在,则赋值undefined

const obj = {
    name: 'lee',
    age: 18
}
let { name, age, gender } = obj;
console.log(gender); // undefined

当指定的属性不存在时,可以定义默认值
默认值在对象上没有该属性或该属性为undefined时生效

const obj = {
    name: 'lee',
    age: 18
}
let { name, age, gender = 'male' } = obj;
console.log(gender); // 'male'

别名(非同名局部变量)

:左边的属性值存储在:右边的变量中

const obj = {
    name: 'lee',
    age: 18
}
let { name: myName, age: myAge } = obj;
console.log(name); // 空
console.log(myName); // 'lee'

嵌套

在解构中使用花括号{},意为在找到花括号{}前的属性后,应该继续深入一层查找花括号{}中的属性

const obj = {
    person: {
        head: {
            eyes: 2,
            mouth: 1
        },
        body: {
            arms: 2,
            legs: 2
        }
    }
}
let { person: {head} } = obj;
console.log(head.eyes); // 2

数组

声明变量

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

赋值变量

let colors = ['red', 'green', 'blue'];
let firstColor = 'black';
let secondColor = 'purple';
[firstColor, secondColor] = colors;
console.log(firstColor); // 'red'

默认值

当指定位置的属性不存在或者其值为nudefined时使用默认值

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

嵌套

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

交换两个值

ES5

let a = 1,
    b = 2,
    temp;

    temp = a;
    a = b;
    b = temp;

ES6

let a = 1,
    b = 2;

[a, b] = [b, a];

不定元素

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

网站导航

网站导航

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 前面的话 我们经常定义许多对象和数组,然后有组织地从中提取相关的信息片段。在ES6中添加了可以简化这种任务的新特性...
    sunnyghx阅读 845评论 0 0
  • 1.在指定默认值时,赋值为<code>null</code>和<code>undefined</code>是不同的...
    请输入其他名字阅读 1,966评论 0 0
  • 具 工具 儿子的摞坨不能玩了,就自己去拿爸爸的工具箱,修半天没有弄好。求助爸爸,同时也认识什么是螺丝刀扳手之内的工...
    Sunny阳光自信的巧克力阅读 501评论 0 1
  • 我今天忘带作业了,和其他忘带作业和没有写作业的人一起接受老师的惩罚—— 写一篇400字的作文。 虽然我知道40...
    杨玉琳阅读 927评论 1 0
  • 生气,是一件很正常的事情,但生闷气就不怎么好了。 当一个人生闷气的时候,会不想搭理别人,脸上满是不愉的表情,心里可...
    翱蓝阅读 894评论 0 1

友情链接更多精彩内容