ES6 rest 参数

400 阅读1分钟

ES6中引入了rest参数,用于获取函数的实参,可以用它来替代arguments

1.在es5中,我们通过arguments来获取实参。它本质上是一个类数组对象,有length属性,也可以通过[]的形式来访问里面的值。

        function fn(){
            console.log(typeof arguments);
            console.log(arguments);
        }

        fn(1,'aa',true);

image.png

2.在ES6中,我们就可以使用rest参数了,它更加的方便

  • 写函数形参时,可以只写一部分,其余的用...args来接收
  • rest参数本质上就是数组,所以与arguments相比较,我们就可以用map,foreach,filter...等方法了,不用再去转一次,十分方便
  • 另外,一般把rest参数放在形参中的最后一位
        function fn(a,...args){
            console.log(args);
            console.log(args.filter(item => typeof item === 'boolean'));
        }

        fn(1,'aa',true);

image.png