变量的解构赋值:从对象或数组中提取数据,并赋值给变量(多个)
对象的解构赋值:let {n,a} = {n:‘tom’,a:12}
数组的解构赋值:let [a,b] = [1,‘atone’];
用途:给多个形参赋值
例:
let obj={name:"xiaozhan",age:29};
// let name = obj.name;
// let age = obj.age;打开这两句话会报错,重复定义
let {name,age} = obj;//let里面的属性是obj里面有的,可以少写
console.log(name,age);
let myarr = [1,3,5,"abc",true];
// let[a,b,c,d,e] = myarr;全取
// let[a,b] = myarr;//取头两个
let[,,a,b]= myarr;//取三、四个
console.log(a,b);
//应用
function foo({name,age}){//{name,age} = obj;
console.log(name,age);
}
foo(obj);
模板字符串:简化字符串的拼接
模板字符串必须要用``包含
变化的部分使用${XXX}定义
例:
let obj1={name:"wt",age:21};
let str = `我的名字叫:${obj1.name},我今年年龄是:${obj1.age}`;
console.log(str);
/*
对象的简写方式:省略同名属性值,省略方法的function
let x=1;
let y=1;
let point = {
x,//this.x = x;
y,//this.y = y;
setX(x){this.x = x};//setX:function(x){};
};
*/
let username1="LLL";
let age1=22;
let obj2 = {
// username1 = username1,
// age1 = age1,
username1,
age1,
// getName:function(){
// return this.username1;
// }
getName(){
return this.username1;
}
};
console.log(obj2);
console.log(obj2.getName());