解构赋值:

将对象、数组、字符串解构分解后赋值给变量
1 、字符串解构赋值
const str1='hello world'
// const a=str1[0]
// const b=str1[1]
// const c=str1[2]
// console.log(a,b,c);
const [a,b,c]=str1
console.log(a,b,c);
下方报错,证明赋值符号前面就是在声明变量,而程序中不能存在重复的变量

 

const str2 = '我有一个梦想'
const [s1, s2] = str2
console.log(s1, s2);
跳过一个或多个

 

const str2 = '我有一个梦想'
const [s1, s2, , s3] = str2
console.log(s1, s2, s3);

 

2 、数组解构赋值
const arr1 = ['清明节', '劳动节', '端午节', '中秋节'];
const [a, b, , c] = arr1
console.log(a, b, c);
3 、对象解构赋值
对象解构赋值与字符串和数组的解构赋值不一样
字符串和数组是根据索引匹配元素
对象根据键寻找值,所以对象解构赋值时,变量名称必须与想要解构的属性名称一致
const person = {
name: '张三',
age: '18',
address: '河北保定',
}
// const name=person.name
// const age=person.age
// 使用解构赋值
const { name, address } = person
console.log(a, b);
解构更复杂的解构
const person = {
name: '张三',
age: '18',
address: {
province: '广东',
city: '深圳',
info: '平安大街1111号'
}
}
// 使用解构赋值
const { name, age,address } = person
console.log(name, age);
// console.log(address);
const {province,city,info} = address
console.log(province,city,info);
也可以使用嵌套的解构赋值简化代码
const person = {
name: '张三',
age: '18',
address: {
province: '广东',
city: '深圳',
info: '平安大街1111号'
}
}
// 使用解构赋值
const { name, age, address: { province, city, info } } = person
console.log(name, age, province, city, info);
补充:被解构的变量无法使用,比如 address
// 案例
const result = {
    data: {
data: [
{ id: 1, title: '历史' },
{ id: 2, title: '军事' },
{ id: 3, title: '情感' },
{ id: 4, title: '校园' },
],
total_page: 10
},
config: {},
response: {}
}
const { data:{data,total_page} } = result
console.log(data);
console.log(total_page);

模版字符串

const name = '张三';
const age = 18;
const address = '北京';
console.log(`${name}几年${age}岁了,居住在${address}`);

声明对象简写

属性声明简写
方法声明简写
当对象中的属性的值是一个变量,而且属性名称与变量名称同名的时候,可以简写
const name = '张三'
const age = 18
const address = '北京'
const person = {
name: name,
age: age,
address: address
}
console.log(person);
如上面代码可以简写为
const name = '张三'
const age = 18
const address = '北京'
const person = {
name,
age,
address
}
console.log(person);
方法简写
const name = '张三'
const age = 18
const address = '北京'
const person = {
name,
age,
address,
speak() {
},
run() {
}
}

  • 14
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值