JS-数组-展开元素 解构赋值
2020-06-13 本文已影响0人
刘淘
1. 展开运算符
(...)三个点叫做展开运算符,允许一个表达式在某处展开。
展开运算符在多个参数(用于函数调用)或多个元素(用于数组字面量)或者多个变量(用于解构赋值)的地方可以使用。
1.通过扩展运算符将数组转换为字符串
2.通过扩展运算符拼接两个数组
image.png
展开运算符在唯一的参数前面的时候,此参数叫做不定参。
如果是在第二个参数后面,可以称之为剩余参数。
image.png
2. 解构赋值
解构赋值是对赋值运算符的扩展。
它针对数组或者对象进行模式匹配,然后对其中的变量进行匹配。
在代码书写上简洁且易读,语义更加清晰明了;也方便了复杂对象中对数据字段的获取。
image.png
不定参+解构赋值综合应用例子:
const data = {
classId: "123456",
className: "qinghua",
one: "one",
two: "two",
three: "three",
four: "four",
employees: [
{ firstName: "Jone1", lastName: "wu", age: 12 },
{ firstName: "Jone2", lastName: "wu", age: 13 },
{ firstName: "Jone3", lastName: "wu", age: 14 },
]
}
//将格式转换为下面的样子:
const data = {
cid: "123456",
cname: "qinghua",
one: "one",
two: "two",
three: "three",
four: "four",
res: [
{ firstName: "Jone1", age: 12 },
{ firstName: "Jone2", age: 13 },
{ firstName: "Jone3", age: 14 },
]
}
//================================
const data = {
classId: "123456",
className: "qinghua",
one: "one",
two: "two",
three: "three",
four: "four",
employees: [
{ firstName: "Jone1", lastName: "wu", age: 12 },
{ firstName: "Jone2", lastName: "wu", age: 13 },
{ firstName: "Jone3", lastName: "wu", age: 14 },
]
}
/**
*参数利用了解构赋值+不定参
*解构应用于函数参数声明,当函数调用时进行解构赋值
*/
function changeObj({ employees, ...others }) {
let newEmployees = []
for (let obj in employees) {
newEmployees.push({
firstName: obj.firstName,
age: obj.age
})
}
return {
cid: others.classId,
cName: others.className,
one: others.one,
res: newEmployees
};
}
let result = changeObj(data);