解构
什么是解构
使用ES6的一种语法规则,将一个对象或数组的某个属性提取到某个变量中
解构不会对被解构的目标造成任何影响
对象解构
在解构中使用默认值
{同名变量 = 默认值}
非同名属性解构
{属性名:变量名}
数组解构
let a = 1, b = 2;
[b, a] = [a, b]
console.log(a, b)//2 1
const numbers = [324, 7, 23, 5, 3243];
// 得到数组前两项,分别放到变量a和b中,然后剩余的所有数据放到数组nums
// const [a, b, ...nums] = numbers;
const a = numbers[0], b = numbers[1], nums = numbers.slice(2);
console.log(a, b, nums);
const article = {
title: "文章标题",
content: "文章内容",
comments: [{
content: "评论1",
user: {
id: 1,
name: "用户名1"
}
}, {
content: "评论2",
user: {
id: 2,
name: "用户名2"
}
}]
}
//解构出第二条评论的用户名和评论内容
// name:"用户名2" content:"评论2"
// const {
// comments: [, {
// content,
// user: {
// name
// }
// }]
// } = article;
// const [, {
// content,
// user: {
// name
// }
// }] = article.comments;
const {
content,
user: {
name
}
} = article.comments[1]
console.log(content, name)
参数解构
function ajax({
method = "get",
url = "/"
} = {}) {
console.log(method, url)
}
ajax()
function print({ name, age, sex, address: {
province,
city
} }) {
console.log(`姓名:${name}`)
console.log(`年龄:${age}`)
console.log(`性别:${sex}`)
console.log(`身份:${province}`)
console.log(`城市:${city}`)
}
const user = {
name: "kevin",
age: 11,
sex: "男",
address: {
province: "四川",
city: "成都"
}
}
print(user)
855

被折叠的 条评论
为什么被折叠?



