ES6——解构赋值

1、解构:按照一定模式,从数组对象中提取值,对变量进行赋值(严格来说是具有Iterator的某种数据结构)。(解构赋值属于浅拷贝)

2、基本用法:模式匹配,等号两边模式一样就会赋值

1)数组

 let [a,b,c]=[1,2,3]
//a=1
//b=2
//c=3
 let [a,b,c]=[1,2,]
//a=1
//b=2
//c=undefined
 let [a,,c]=[1,2,3]
//a=1
//c=3
 let [a,...b]=[1,2,3]
//a=1
//b=[2,3]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4

2)对象(根据对应的属性名匹配,如果没有则为undefined)

let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"

let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined

const { log } = console;
log('hello') // hello

//赋值的是变量,此时foo事模式
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined

let obj = {
  p: [
    'Hello',
    { y: 'World' }
  ]
};

let { p, p: [x, { y }] } = obj;
x // "Hello"
y // "World"
p // ["Hello", {y: "World"}]

3)字符串解构赋值(优先转为对象)

let {length : len} = 'hello';//相当于在‘length'这个类数组对象中寻找雨’length‘同名的属性赋值
len // 5
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"

4)数值和布尔值的解构赋值(优先转为对象)

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true

5)函数参数的解构赋值

function move({x = 0, y = 0} = {}) {
  return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]

function move({x, y} = { x: 0, y: 0 }) {
  return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]
//以上两者的区别在于第一种将值赋给了参数,第二种将参数作为一个对象统一赋值,所以只用在参数对象为undefined时才取默认值
[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]

3、默认值(当一个元素解构获得的值严格等于(===)undefined,默认值才生效)

let [foo = true] = [];
foo // true

let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
//当默认值为表达式时,只有当解构的值为undefined时才会执行
function fu(){
    return 31}
let [a=fu()]=[3]//3,且fu不执行
let [a=fu()]=[]//31,且fu()执行
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值