ES6 扩展运算符和剩余操作符

扩展运算符
1.改变函数调用
   var students = ['Abby','Andy'];
   var otherStudents = ['Jane','Tom'];
   students.push(...otherStudents);
   console.log(students); // Abby Andy Jane Tom

2.数组构造
   var parts = ['shoulders', 'knees'];
   var lyrics = ['head', ...parts, 'and', 'toes'];
   console.log(lyrics)// ['head', 'shoulders, 'knees', 'and', 'toes']

3.数组解构
   var students = ['Abby', 'Andy', 'Jane', 'Tom'];
   var somestudents, otherStudents;
    [somestudents, ...otherStudents] = students ;
    console.log(somestudents); // Abby
    console.log(otherStudents); // Andy Jane Tom

4.将类数组对象转换成数组
   var nodeList = document.querySelectorAll('div');
   var array = [...nodeList];

5.React 里面的延展属性(Spread Attributes)
   var props = {};
    props.foo = x;
    props.bar = y;
    var component = <Component {...props} />;
    它能被多次使用,也可以和其它属性一起用。注意顺序很重要,后面的会覆盖掉前面的。
     var props = { foo: 'default' };
     var component = <Component {...props} foo={'override'} />;
     console.log(component.props.foo); // 'override'

剩余操作符
1.获取参数
function fn(a, b, ...args) {
   return args.length;
}
fn(1, 2, 3, 4, 5 ); // 传进来的参数的个数 3
其中第一个形参 a 对应的是 1,第二个形参 b 对应的 2,…args 表示的就是[3, 4, 5]。

2.与 arguments 的不同
    arguments 想要变成数组,可以通过 Array.prototype.slice.call 方法,使用剩余操作符可以避免将 arguments 转为数组的麻烦。这种用法和上面 扩展运算符的用法还有点异曲同工之妙。
     // 下面的代码模拟了剩余数组
    function fn1(a, b){
       var args = Array.prototype.slice.call(arguments, fn1.length);
       console.log(args.length);
    }
    // 现在代码可以简化为这样了
    function fn2(a, b, ...args) {
       console.log(args.length);
    }
    fn1(1,2,3); // 1
    fn2(1,2,3); // 1

扩展运算符与剩余操作符的区别
关于扩展运算符与剩余操作符之间的区别,简单地说,在某种程度上,剩余操作符和扩展运算符相反,扩展运算符会“展开”数组变成多个元素,剩余操作符会收集多个元素和“压缩”成一个单一的元素。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容