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;

 

 

 

你可能感兴趣的:(ES6)