arguments 是函数内部的实参集合,箭头函数没有 arguments,用 ...rest 剩余参数代替。
核心三种:
① arguments——所有实参,类数组
② ...rest——剩余参数,真数组
③ 箭头函数——没有自己的 this 和 arguments
坑:arguments 不能用数组方法、箭头函数不能当构造函数、rest 参数必须放最后。
每个函数肚子里都藏着一个 arguments,装着所有丢进来的料。它有 length、能按编号取,但没有 push/pop 这些数组方法,所以叫「伪数组」——长得像数组,其实不是真的。
function getMax() {
// 先假设第一个是最大
let max = arguments[0];
// 挨个比,遇到更大的就换
for (let i = 1; i < arguments.length; i++) {
if (arguments[i] > max) max = arguments[i];
}
// 把最大的递出去
return max;
}
// 比完 → 99
getMax(1, 99, 23, 66);
...rest 收进来的是真数组,数组该有的方法它全有,比 arguments 好用。必须放在投料口最后一位。
// 前两个正经接,剩下的全收进 rest
function sum(a, b, ...rest) {
// 1 2
console.log(a, b);
// [3,4,5],是真数组
console.log(rest);
let total = 0;
// 把 rest 挨个加起来
for (let n of rest) total += n;
// 递出去
return total;
}
sum(1, 2, 3, 4, 5);
// 普通函数表达式
// 箭头函数完整写法:把 function 换成 =>
let add = function (a, b) { return a + b; };
// 偷懒1:只有一行 return,{} 和 return 都能省
let add = (a, b) => { return a + b; };
// 偷懒2:只有一个投料口,连小括号都能省
let add = (a, b) => a + b;
let double = n => n * 2;
如果你拿箭头函数去当对象里的方法,this 就会跑偏。因为箭头函数不自己认 this,它的 this 是从外层「借」来的,而且它没有 arguments。所以它不适合做对象方法、不适合做事件处理;但写小回调、短计算特别顺手。
① 用在哪:写小回调、事件处理里的短函数、求和求最大这种参数个数不定的功能。
② 常见坑:拿箭头函数做对象方法,this 跑偏;用老的 arguments 却想调用数组方法。
③ 怎么解决:参数不定用 ...rest(真数组);对象方法/事件用普通函数,别用箭头函数。
| API | 作用 | 参数 | 返回值 | 代码示例 |
|---|---|---|---|---|
| ...rest | 剩余参数:把多收的装进真数组 | 任意个参数 | 数组 | function sum(...nums) {
return nums;
} |
| (a,b)=>{} | 箭头函数,简写 | 参数 | 函数 | let add = (a, b) => a + b; // 箭头函数简写 |
| 箭头函数 this | 没有自己的 this,继承外层 | 无 | 外层 this | let hi = () => this; // 不自己认 this |