ES6-函数的扩展

rest参数
rest参数(形式为...变量名)用来获取函数的多于参数。

  • rest参数的变量是一个数组用来将多余的参数放入数组
  • rest参数后面不能有其他参数,否则会报错
  • ES6函数的length属性不包括rest参数
function add(...values) {
  let sum = 0;

  for (var val of values) {
    sum += val;
  }

  return sum;
}

add(2, 5, 3) // 10

rest参数与arguments的比较

// arguments变量的写法
function sortNumbers() {
  return Array.prototype.slice.call(arguments).sort();
}

// rest参数的写法
const sortNumbers = (...numbers) => numbers.sort();
  • Array.prototype.slice.call将参数arguments转化成数组
  • slice()用来提取字符串
    ES6箭头函数
    如果箭头函数返回的是一个对象则需要在对象外加括号,应为对象有大括号,大括号会被解为代码块。
// 报错
let getTempItem = id => { id: id, name: "Temp" };

// 不报错
let getTempItem = id => ({ id: id, name: "Temp" });

箭头函数与rest参数结合使用

const numbers = (...nums) => nums;

numbers(1, 2, 3, 4, 5)
// [1,2,3,4,5]

const headAndTail = (head, ...tail) => [head, tail];

headAndTail(1, 2, 3, 4, 5)
// [1,[2,3,4,5]]

箭头函数的注意事项

1.函数体内的this对象,就是定义时所在的对象,而不是使用时所在对象(全局对象)
2.因为箭头函数没有this对象所以不能当作构造函数,不能使用new命令
3.不能使用arguments对象,用rest代替
4.不能使用yield命令

参考链接

原文地址:https://www.cnblogs.com/yuanchao-blog/p/10844660.html