Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:完成的不错, 继续加油
实例演示对象与数组的解构赋值
解构语法
模板 = 集合(数组,对象)
数组
let [uname, email] = ['杨过', '123@qq.com']
console.log(uname, email)
更新
在 [],{},()之前的分号不能省略
;[uname, email] = ['小龙女', '1456@qq.com']
console.log(uname, email)
1. 值数量 < 变量数量, 默认值
;[uname, email, gender = '女'] = ['潘金莲', '789@qq.com']
console.log(uname, email, gender)
2. 值数量 > 变量数量, ...rest
;[uname, ...arr] = ['潘金莲', '789@qq.com', '女']
console.log(uname, arr)
console.log(uname, ...arr)
应用场景: 交接二个数
let x = 10
let y = 20
console.log(`x = ${x}, y = ${y}`)
;[y, x] = [x, y]
console.log(`x = ${x}, y = ${y}`)
变量名 === 属性名
let { num, price } = { num: 2, price: 5000 }
console.log(num, price)
[],{},()之前分号不能省略
{}不能出现在等号左边(左值),所以加上括号()转成表达式
;({ num, price } = { num: 5, price: 6000 })
console.log(num, price)
命名冲突: 别名
let { pname, price: uniPrice } = { pname: '手机', price: 8000 }
访问用别名
console.log(pname, uniPrice)
应用场景1: 克隆对象
let lesson = { name: 'ES6', score: 88 }
console.log(lesson)
如果想创建二个不相关的对象,值又完全一样,只能克隆
let { ...obj } = lesson
console.log(obj)
console.log(obj === lesson)
应用场景2 : 解构传参
let show = function (user) {
user 是一个对象
return `${user.uname}: ( ${user.email} )`}
let user = { uname: '朱老师', email: '498668472@qq.com' }
console.log(show(user))
使用对象解构进行简化传参
show = function ({ uname, email })
{return `${uname}: ( ${email} )`}
user = { uname: '钟老师', email: '45678@qq.com' }
console.log(show(user))
let course = {
lesson: {
name: 'ET7',
score: 60,
},
getScore() {
return {
name: this.lesson.name,
course: this.lesson.score,
}
},
setScore(score) {
if (score >= 0 && score <= 100) {
this.lesson.score = score
} else {
console.log('成绩必须在1-100分之间')
}
},
}
console.log(course.lesson.score)
console.log(course.getScore())
course.setScore(69)
console.log(course.getScore())