将对象、数组、字符串解构分解后赋值给变量 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() {
}
}
标签:const,name,age,解构,address,console,赋值
From: https://blog.csdn.net/m0_59365887/article/details/139183306