解构赋值
解构赋值的应用场景
1.当数组/对象作为函数参数时
const fun = ([a, b, c]) => {
console.log(a + b + c)
}
fun([1, 2, 3])
const fun1 = ({ name, age }) => {
console.log(name, age)
}
fun1({
name: 'cc',
age: 18
})
2.当数组/对象作为函数的返回值时
const fun2 = () => {
return [1, 2, 3]
}
const [one, two, three] = fun2()
console.log(one, two, three)
const fun3 = () => {
return {
job: 'Engineer',
workingAge: 1
}
}
const { job, workingAge } = fun3()
console.log(job, workingAge)
3.两个变量互换值 使用解构赋值更简单些
let a = 1;
let b = 2;
[a, b] = [b, a]
console.log(a, b)
4.JSON应用(与第5个应用场景一样)
const json = '{"name":"cc","age":"18"}'
const { name, age } = JSON.parse(json)
console.log(uname, uage)
5.发起ajax请求时
axios.get('url').then(({data: res})=>{
console.log(res)
})