Blogger Information
Blog 25
fans 0
comment 0
visits 9449
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
前端开发-对象与数组的解构赋值20221103
P粉114035831
Original
355 people have browsed it

对象与数组的解构赋值

* 1.数组

建变量数组

let [uname,email]=[‘老王’,’asd@qq.com’]
console.log(uname,email)
//更新
//在[],{},()之前的分号不能省略
;[uname,email] = [‘老张’,’qwe@qq.com’]
console.log(uname,email)
console.log(‘———————‘)

A.值数量 < 变量数量,默认值

//无法识别出 “gender”需要对其赋值
;[uname,email,gender] = [‘小芳’,’zxc@qq.com’]
console.log(uname,email,gender)
//对”gender”赋值’女’后就能被打印
;[uname,email,gender=’女’] = [‘小芳’,’zxc@qq.com’]
console.log(uname,email,gender)

B.值数量>变量数量,则需要使用…rest

;[uname,…arr] = [‘小芳’,’zxc@qq.com’,’女’]
//打印出一个数值和(把数组后面二个字符口串放到一个数组显示)数组
console.log(uname, arr)
//打印出数值,都展开显示
console.log(uname,…arr)
console.log(‘————————-‘)

//应用场景:交接二个数
//建二个变量以方便交换
let x = 10
let y = 30
//交换方式
;[y,x] = [x, y]
//使用反式符
console.log(x=${x},y=${y})
console.log(‘———————-‘)

* 2.对象解构

变量名 === 属性名

//创建变量
let {num, price} = {num:1, price:2000}
console.log(num,price)
//更新.{}不能出现在等号左边(左值),所以加上括号()转成表达式
;({num,price} = {num:2, price:3000})
console.log(num, price)

//命名与前面的冲突,则需要另起一个别名
let { pname, price:block} = { pname:’电脑’, price:3000}
//访问时要用别名
console.log(pname, block)
console.log(‘———————————-‘)

应用场景1: 克隆对象

let lesson = { name: ‘text’, score:11 }
console.log(lesson)
//如果想创建二个不相关的对象,值又完全一样,只能克隆
let {…obj} = lesson
console.log(obj)
// obj不等于lesson
console.log(obj === lesson)
console.log(‘———————————-‘)

应用场景2:解构传参

let show = ({uname, email})=> {return ${uname},${email}}

user= {uname:’老王’, email:’qwe@qq.com’}
console.log(show(user))

* 访问器属性

let course = {
lesson:{
name:’老王’,
score:60,
},

getScore (){
return {
name:this.lesson.name,
course:this.lesson.score,
}
},

setScore(score)
{this.lesson.score = score
}
}

console.log(course.lesson.score)

普通方法 ===> 访问器属性

getScore ===> get score

使属性方法化

course = {
lesson:{
name:’老王’,
score:60,
},
get score (){
return {
name:this.lesson.name,
course:this.lesson.score,
}
},

  1. set score(score)
  2. {this.lesson.score = score
  3. }
  4. }

console.log(course.score)

访问器属性方法化后,简化了代码

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post