let array = ["LO","VE","LOVE"]; //一个数组
let [a,b,c] = array; //解构符号内声明三个变量,对应array数组中的三个值
console.log(a,b,c);
let str1 = "LO"; //三个变量
let str2 = "VE";
let str3 = "LOVE";
[str1,str2,str3] = [str2,str1,str3]; //注意这里不用使用let再次定义了
console.log(str1,str2,str3);
let array = ["LO","VE","LOVE","JW","SNOW"]
let [str1,str2,str3] = array; //默认以数组的索引开始赋值
console.log(str1,str2,str3);
let array = ["LO","VE","LOVE","JW","SNOW"]
let [str1,str2,,,str3] = array; //对不想要的值空格显示/直接','
let [ , , , , ,str6] = array; //当超出数组长度时,会默认赋值undefined
console.log(str1,str2,str3,str6);
let array = ["LO","VE","LOVE","JW","SNOW"]
let {0:str1,3:str2,4:str3} = array; //中括号改成花括号,
console.log(str1,str2,str3);
let array = ["LO","VE","LOVE","JW","SNOW"]
let [str1 = "snow"] = [undefined];
let [str2 = "snow"] = array;
// str1 = "snow" 其中snow为默认值,
//只有当解构模式有匹配结果,且匹配结果是 undefined 时,才会触发默认值作为返回结果,否则就是对应的元素
console.log(str1,str2);
let array = ["LO","VE","LOVE","JW","SNOW"]
let [str1, ,...str] = array;
console.log(str1,str);
语法一:let关键字+{变量名1}(大括号:关键符号,代表解构,里面存放变量)= {属性名1:属性值}(也可以是对象名);
let obj = {
id:'1',
name: '❆VE❆',
age: '20',
sex: '男',
email:'[email protected]'
}//对象及对象中的五个属性
let {name, age, email} = obj //解构变量与obj对象中的几个属性名一一匹配
console.log(name,age,email)
语法二:let关键字+{变量名1:新的变量名1}(大括号:关键符号,代表解构,里面存放变量)= {属性名1:属性值}(也可以是对象名);
let obj = {
id:'1',
name: '❆VE❆',
age: '20',
sex: '男',
email:'[email protected]'
}//对象及对象中的五个属性
let arr = ['name','age','email']
let {[arr[0]]:myName, [arr[1]]:myAge, [arr[2]]:myEmail} = obj //解构变量与obj对象中的几个属性名一一匹配
console.log(myName,myAge,myEmail)
let obj = {
id:'1',
name: '❆VE❆',
age: '20',
sex: '男',
email:'[email protected]'
}//对象及对象中的五个属性
let {name:myName,age:myAge,email:myEmail = "[email protected]",lover:myLover = "snow"} = obj
console.log(myName,myAge,myEmail,myLover)
let obj = {
id:'1',
name: '❆VE❆',
age: '20',
sex: '男',
email:'[email protected]'
}//对象及对象中的五个属性
let {name:myName,age:myAge,...restObj} = obj
console.log(myName,myAge,restObj)
let obj = {
id:'1',
name: '❆VE❆',
detail:{
age: '20',
sex: '男',
contact:{
qq: '480353464',
email:'[email protected]'
}
}
}//多维对象
let {detail:{contact:{qq}}} = obj // 注意嵌套到里层的变量需要添加{}
console.log(qq)
例子:
let arr = [
{name: "❆LO❆",age:"18"},
{name: "❆VE❆",age:"19"},
{name: "❆LOVE❆",age:"20"}
]
arr.forEach((item,index)=>{
console.log('name:'+item.name+',age:'+item.age)
})
console.log("-------------------")
arr.forEach(({name,age},index)=>{
console.log('name:'+name+',age:'+age)
})
let obj = {
id:'1',
name: '❆VE❆',
detail:{
age: '20',
sex: '男',
contact:{
qq: '480353464',
email:'[email protected]'
}
},
habbit:[
"羽毛球",
{
time:"2018"
}
]
}//多维对象
let {habbit:[str,{time},add]} = obj
console.log(str,time,add)