ES2015入门系列6-Rest和Spread

ES2015为咱们带来了一个新的操做符: ...,javascript

  • 用于定义函数参数的地方,称之为 Restjava

  • 用于调用函数的地方,称之为 Spread数组

咱们一个个来分析:函数

  • Restthis

写程序的时候或多或少都会有,传入不定参数给一个函数的需求,如,给一个班级加入学生名单,能够一次给一个,也能够一次给多个,之前的作法,多是传入数组,或者定义2个方法,一个传入单个学生,一个传入学生数组,如:code

class ClassRoom {

  constructor(name) {
     this.name = name;
     this.students = [];
  }

  addStudent(name) {
    this.students.push(name);
  }

  addStudents(names) {
    this.students = this.students.concat(names);
  }

  listStudents() {
     console.log(this.students);
  }

}

const classRoom = new ClassRoom('三年二班');
classRoom.addStudent('张三');
classRoom.addStudents(['李四', '王五']);
classRoom.listStudents();

有了 Rest 咱们的代码就简单了,ip

class ClassRoom {

  constructor(name) {
     this.name = name;
     this.students = [];
  }

  addStudents(...names) {
    this.students = this.students.concat(names);
  }

  listStudents() {
     console.log(this.students);
  }

}

const classRoom = new ClassRoom('三年二班');
classRoom.addStudents('张三');
classRoom.addStudents('李四', '王五');
classRoom.listStudents();

代码中的...names, 意思就是: 从我开始无论后面有多少参数,请帮我把它们组成数组给我后面的参数。 如此一来,也能够这样,io

function callFriends(via, ...friends) {
  console.log('使用' + via + '通知: ' + friends.join(',') + '等' + friends.length + '个好友');
}
callFriends('QQ', '张三');
callFriends('电话', '张三', '李四', '王五');

结果:console

> 使用QQ通知: 张三等1个好友
> 使用电话通知: 张三,李四,王五等3个好友

应用刚才的解释到这里,从...开始,无论后面有多少个朋友传进来,请把他们组成数组放入friends参数给我。function

  • Spread

Spread 就是 Rest 的逆操做,看代码:

计算一个数组(大于三个元素)中前三个元素的和以及全部元素的和。

function sum(x, y, z, ...r) {
  let firstThree = x + y + z;
  let total = x + y + z + r.reduce((left, right) => left + right);
  console.log('前三个值为: ' + firstThree);
  console.log('总和为: ' + total);
}
sum(...[1, 2, 3, 4]);
sum(...[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

结果:

> 前三个值为: 6
> 总和为: 10
> 前三个值为: 6
> 总和为: 55
相关文章
相关标签/搜索