rest参数

ES6 引入 rest 参数,用于获取函数的实参,用来代替 arguments 。

与arguments不同的是,arguments返回的是一个对象,而rest函数返回的是一个数组,便于我们使用forEach()、filter()、map()、some()、every()去操作数组。

注意:rest函数必须放在参数最后,否则会报错

 

 下面是一个 rest 参数代替arguments变量的例子。
// arguments变量的写法
function sortNumbers() {
  return Array.prototype.slice.call(arguments).sort();
}

// rest参数的写法
const sortNumbers = (...numbers) => numbers.sort();

arguments对象不是数组,而是一个类似数组的对象。所以为了使用数组的方法,必须使用Array.prototype.slice.call先将其转为数组。rest 参数就不存在这个问题,它就是一个真正的

数组,数组特有的方法都可以使用。下面是一个利用 rest 参数改写数组push方法的例子。

函数的length属性,不包括 rest 参数。

(function(a) {}).length   //1
(function(...a) {}).length   //0
(function(a,...b) {}).length   //1
posted @ 2022-05-24 16:18  yeqi7  阅读(362)  评论(0)    收藏  举报