解构
什么是解构
使用ES6的一种语法规则,将一个对象或数组的某个属性提取到某个变量中
解构不会对被解构的目标造成任何影响
对象解构
在解构中使用默认值
{同名变量
= 默认值
}
非同名属性解构
{属性名
:变量名
}
数组解构
let a
= 1, b
= 2;
[b
, a
] = [a
, b
]
console
.log(a
, b
)
const numbers
= [324, 7, 23, 5, 3243];
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"
}
}]
}
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
)
转载请注明原文地址: https://lol.8miu.com/read-7227.html