JavaScript 3.5 解构赋值

一、数组模型结构

1、基本
let [a, b, c] = [1, 2, 3];
output:
 a = 1
 b = 2
 c = 3

2、可嵌套
let [a, [[b], c]] = [1, [[2], 3]];
output:
 a = 1
 b = 2
 c = 3

3、可忽略
let [a, , b] = [1, 2, 3];
output:
 a = 1
 b = 3

4、不完全解构
let [a = 1, b] = []; 
output:
 a = 1, b = undefined

5、剩余运算符
let [a, ...b] = [1, 2, 3];
output:
a = 1
b = [2, 3]

6、字符串
let [a, b, c, d, e] = 'hello';
output:
a = 'h'
b = 'e'
c = 'l'
d = 'l'
e = 'o'

在数组的解构中,解构的目标若为可遍历对象,皆可进行解构赋值。
可遍历对象即实现 Iterator 接口的数据

7、解构默认值
let [a = 2] = [undefined];
output:
a = 2

二、对象模型Object解构

1、基本
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
output:
 foo = 'aaa'
 bar = 'bbb'
 
let { baz : foo } = { baz : 'ddd' };
output:
 foo = 'ddd'

2、可嵌套可忽略

let obj = {p: ['hello', {y: 'world'}] };
let {p: [x, { y }] } = obj;
output:
 x = 'hello'
 y = 'world'
let obj = {p: ['hello', {y: 'world'}] };
let {p: [x, {  }] } = obj;
output:
 x = 'hello'

3、不完全解构
let obj = {p: [{y: 'world'}] };
let {p: [{ y }, x ] } = obj;
output:
 x = undefined
 y = 'world'

4、剩余运算符
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
output:
 a = 10
 b = 20
 rest = {c: 30, d: 40}

5、解构默认值
let {a = 10, b = 5} = {a: 3};
output:
 a = 3; b = 5;
let {a: aa = 10, b: bb = 5} = {a: 3};
output:
 aa = 3; bb = 5;

参考:https://www.runoob.com/w3cnote/deconstruction-assignment.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值