ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。
var arr = ['张三','李四','王五','物流'];
var a = arr[0];
var b = arr[1];
var c = arr[2];
var d = arr[3];
console.log(a,b,c,d);
这种写法相当于‘模式匹配’,只要等号两边的模式相同,左边的变量就会被赋予arr中相对应的值
var arr = ['张三','李四','王五','物流'];
let [a,b,c,d] = arr;
console.log(a,b,c,d);
如果解构不成功,变量的值就等于undefined
var obj = {
myname:'小乐',
age:12,
height:'134cm'
};
var myname = obj.myname;
var myage = obj.age;
var myheight = obj.height;
console.log(myname,myage,myheight);
对象的解构相对于数组有一个重要的不同,数组的元素按依次排序就能匹配到相应的值,也就是说变量的取值由位置决定;而对象有键名和键值,所以变量必须与属性同名,才能取到正确的值(变量与属性同名可省略特性)
var obj = {
myname:'小乐',
age:12,
height:'134cm'
};
//变量与属性同名时
let {myname,age,height} = obj;
console.log(myname,myage,height);
//变量与属性不同名
let {myname:name,age:myage,height:myheight} = obj;
console.log(name,myage,myheight);
输出:
小乐 12 134cm
let {myname:myname1,age:myage,height:myheight} = obj;
console.log(myname1,myage,myheight);
var obj1 = {
myname:'小乐',
age:12,
hobby:{
one:1,
two:2
},
height:123,
arr:[1,2,3]
};
let {myname:myname1,age:myage,hobby:{one:myone,two:mytwo},height:myheight,arr:[a,b,c]} = obj1;
console.log(myname1,myage,myone,mytwo,myheight,a,b,c);
let {myname:myname1,age:myage,height:myheight} = obj;//键名和键值
let {myname,age,height} = obj;//键名和键值 需要一样 ,你可以省略一个 名称和 冒号
function fn({myname,age}){
console.log(myname,age);
};
fn({myname:'小乐',age:145});
var str = 'suygfcush';
let [a,b,c,d,e,f,g] = str;
console.log(a,g);
输出:
s u
函数的参数可以使用解构赋值
//利用数组的形式传递可以使用的解构赋值
function fn([a,b]){
console.log(a,b);//输出:100,200
};
fn([100,200]);
//利用对象的形式传递解构赋值
function demo({name, age}) {
console.log(name, age);//输出:100,200
}
demo({name: 100, age: 200});
//参数可以设置默认值
function d({id, autoPlay=false, duration=3000, click=false}){
console.log(id, autoPlay, duration, click);//输出:#myPlay,true,5000,faluse
};
d({ id: '#myPlay',
autoPlay: true,
duration: 5000,})
var x = 1;
var y = 2;
[x,y] = [y,x];
let jsonData = {
id:42,
status: "OK",
data: [867, 5309]
};
let {id,status,data} = jsonData;
consloe.log(id,status,data);//输出: 42 'OK' [867, 5309]
function getInfo() {
return {
name: '曹操',
age: 100
}
}
let {name, age} = getInfo();
console.log(name, age); //输出:'曹操' 100