一、剩余参数和扩展运算符
1. 剩余参数
1.1 剩余参数是什么
- 剩余参数的作用:将传入的参数组合为一个数组,即使没有传值,也会是一个空数组
- 语法:通过
...参数名
定义,使用时直接使用对应参数名即可
const add = (x,y,...args) => {
console.log(args)
}
add(1,2,3,4,5,6,7)
1.2 剩余参数的注意事项
- 箭头函数的参数部分即使只有一个剩余参数,也不可以省略圆括号
const num = x => {
console.log(x)
}
const add = (...args) => {
console.log(args)
}
num(1)
add(5,2,3,4)
- 使用剩余参数代替 arguments 获取实际参数
- arguments 是一个
类数组对象
,JS在调用函数时传递的参数就会被 arguments 收集到
const fun = function() {
console.log(arguments)
}
fun('嘟嘟',18,'女')
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d9cbf3f35ed762bbacd083f783741eda.png)
- 箭头函数无arguments对象,可以通过剩余参数来代替
const fun = (...args) => {
console.log(args)
}
fun('嘟嘟',18,'女')
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c7ebfb9169e64d866cd301a47f46b5d5.png)
剩余参数只能放在参数列表的最后
,剩余参数的后面不能再有其他参数,否则会报错,剩余参数的前面可以有其他参数
1.3 剩余参数的应用
- 当不明确传入的实参有多少时,可以使用剩余参数接收所有的参数
const add = (...args) => {
let sum = 0
for(let i = 0; i < args.length; i++) {
sum += args[i]
}
return sum
}
console.log(add(8,2,9,10,23,87))
- 剩余参数与解构赋值结合使用(剩余元素)
- 剩余参数不一定要作为函数参数使用
- 不管如何使用,都必须满足:
剩余参数必须位于最后
const [a,...args] = [1,23,13,14,15]
console.log(args)
const {
x,y,...args1} = {
x:12,y:19,z:829,i:31,j:12}
console.log(x,y,args1)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/22db609694477eb9966bff0e73a1ca7b.png)
2. 扩展运算符
- 扩展运算符的作用:合并多个数组或对象
- 有扩展运算符的变量要放最后
- 语法:
...变量名
3. 剩余参数和扩展运算符的区别
4. 数组的扩展运算符
function foo(a,b,c) {
console.log(a)
console.log(b)
console.log(c)
}
let arr = [1,2,3]
foo(...arr)
4.1 利用扩展运算符复制数组
const a = [1,2]
const b = a;
const c = [...a]
a[0] = 7
console.log(b)
console.log(c)
4.2 利用扩展运算符合并数组
const ARRAY1 = [1,2,3]
const ARRAY2 = ['a','b']
const ARRAY3 = ['我是数组']
const ARRAY = [...ARRAY1,...ARRAY2,...ARRAY3]
console.log(ARRAY)
4.3 利用扩展运算符将字符串转为数组
console.log([...'你好嘟嘟'])
4.4 利用扩展运算符将类数组转换为数组
function add() {
console.log([...arguments]);
}
add(2,8,19,10)
5. 对象扩展运算符
5.1 扩展运算符复制对象
const person = {
name:'嘟嘟',
age:19,
sex:'女'
}
console.log({
...person})
5.2 扩展运算符合并对象
const person = {
name:'嘟嘟',
age:19,
sex:'女'
}
const person1 = {