对象成员简写
- 现在声明一个对象
- 对象里面有name,age,gender,score属性
- 希望这些属性的值是上面对应变量的值
测试代码
//es5
/*
var obj = {
name:name,
age:age,
gender:gender,
score:score,
sayHi:function(){
console.log('你好');
}
}
console.log(obj)
obj.sayHi()
*/
//es6
var obj = {
name,
age,
gender,
score,
fenshu:score,
sayHi(){
console.log('你好')
}
}
console.log(obj)
obj.sayHi()
对象解构赋值
- 取对象中属性的值,赋值给变量
测试代码
//声明一个变量
let obj = {
name:'111',
age:29,
gender:'男',
score:100
}
/*
es5
let name1 = obj.name;
let age1 = obj.age;
let gender1 = obj.gender;
let score1 = obj.score;
console.log(name1,age1,gender1,score1)
*/
/*
es6
a.
let {name:name1,age:age1,gender:gender1,score:score1} = obj;
console.log(name1,age1,gender1,score1)
*/
/*
b.
let {name:name.age:age,gender:gender,score:score}
console.log(name,age,gender,score)
*/
/*
c.如果声明的变量名和对象属性名一致,可以简写
let {name,age,gender,score};
console.log(name,age,gender,score)
*/
/*
d.obj中没有属性,输出为undefined
let {name,age,gender,fenshu}
console.log(name,age,gender,fenshu)
*/
/*
e.fenshu取score属性的值
let {name,age,gender,score:fenshu}
console.log(name,age,gender,fenshu)
*/
/*
f.使变量有默认值
let {name,age,gender,fenshu=120}
console.log(name,age,gender,fenshu)
*/
展开运算符/对象展开
测试代码
//声明一个对象
let fn = {
name:'111',
age:29,
sayHi(){
console.log('测试')
}
}
//声明一个对象
let fun = {
name1:'222',
age1:20
}
//声明一个对象
let linge = {
//name2:'333',
//age2:29,
//sayHi(){
// console.log('测试')
//},
//shill:'444',
//song:'333'
//展开语法
...fn,
...fun,
gender:'男',
age:49
}
console.log(linge)