视频加载失败

ES6剩余参数

459 字
2 分钟
ES6剩余参数

剩余参数是什么#

剩余参数(Rest Parameters)是 ES6 提供的一种语法,用来把函数中“多出来的参数”收集成一个数组。把不确定数量的参数打包成一个数组

const add = (...args) => {
console.log(args);
};
add(1, 2, 3, 4, 5, 6, 7, 8, 9);//[1,2,3,4, 5, 6, 7, 8, 9 ]

剩余参数的本质:是数组

const add = (x, y, z, ...args) => {
console.log(x, y, z, args);
};
add(1, 2, 3, 4, 5, 6, 7, 8, 9);//1 2 3 [ 4, 5, 6, 7, 8, 9 ]

剩余参数的注意事项#

箭头函数的剩余参数

const add = (...args) => {
//即使只有一个剩余参数,括号不能省略
console.log(args);
};
add(1, 2, 3, 4, 5, 6, 7, 8, 9);

代替arguments获取实际参数

//箭头函数没有arguments
// const add = () => {
// console.log(arguments);
// };
// add(1, 2);
//普通函数获取剩余参数
// const add1 = function () {
// console.log(arguments[0]); //{ '0': 1, '1': 2 }类数组
// };
// add1(1, 2);
//箭头函数获取剩余参数
const add = (...args) => {
console.log(args); //[ 1, 2 ]真数组
};
add(1, 2);

剩余参数的书写位置

//剩余参数的书写位置:只能写到最后,否则报错
const add = (...args,x) => {
console.log(args); //[ 1, 2 ]真数组
};
add(1, 2);//报错

剩余参数的应用#

//参数累加
// const add = (...args) => {
// let sum = 0;
// for (let i = 0; i < args.length; i++) {
// sum += args[i];
// }
// return sum;
// };
// console.log(add(1, 2));
//必须最后一个
// const [num, ...args] = [1, 2, 3, 4, 5, 6];
// console.log(num, args);
//数组参数也能使用
// const func = ([num, ...args]) => {
// console.log(num, args);
// };
// func([1, 2, 3]);
// const { x, y, ...z } = { a: 3, x: 1, y: 2, b: 4 };
// console.log(x, y, z); //输出 1 2 { a: 3, b: 4 }
const func = ({ x, y, ...z }) => {
console.log(x, y, z);
};
func({ a: 3, x: 1, y: 2, b: 4 });

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

ES6剩余参数
https://f.youzi177.cn/posts/2026102106es6-sheng-yu-can-shu/
作者
小封鸭
发布于
2026-10-21
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
小封鸭
小楼一夜听春雨,深巷明朝卖杏花
公告
欢迎来到我的博客。这里主要记录前端全栈和日常内容
分类
标签
最新动态
站点统计
文章
60
分类
3
标签
12
总字数
107,734
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
EdgeOne Pages
博客版本
Firefly v6.16.8
文章许可
CC BY-NC-SA 4.0
文章目录