ES6变量解构赋值

ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构。

ES6对象解构,直接看代码:

const tom={

name:'tom',

age:20,

family:{

mother:'Mary',

father:'Smith',

brother:'Jone'

}

}

const {name,age}=tom;

const {mother,father,brother}=tom.family;//意思是在tom.family里面找属性名为mother,father,brother的属性,把值赋给大括号里面的mother,father,brother

当按照下面这样写的时候,代表是重新命名,要使用的时候需要用mother

const mother='Rose'

const {mother,father,brother}=tom.family;

consloe.log(mother);//会报错这是需要我们重命名写法如下:

const mother='Rose'

const {mother:m,father,brother}=tom.family;//这时const声明的mother变量重新命名为m

consloe.log(m);

这是不能再使用mother,要使用新名称m

如果获取一个对象里面没有的属性

const {mother,father,brother,sister}=tom.family;

consloe.log(sister);//undefined

给属性默认值:

const {mother,father,brother,sister='have no sister'}=tom.family;//当sister的值为undefined是就使用默认值。

数组解构赋

值:

const number=['one','two','three','four'];

const [one, ,three];

console.log(one);

console.log(three);

如果只想获取数组的第一个元素和后面的所有元素,可以使用ES6提供的剩余参数的形式:

const number=['one','two','three','four'];

const [one,...others];

console.log(one);//one

console.log(others);//['two','three','four']

数组解构默认值

const detail=['jelly','Mary.com']

const [name,webite,category='java']=detail;

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值