函数参数的默认值

  1. // demo1
  2. // ES5
  3. function log(x, y) {
  4. y = y || 'World';
  5. console.log(x, y);
  6. }
  7. log('Hello');
  8. log('Hello', 'China');
  9. log('Hello', '');
  10. // ES6
  11. function log(x, y = 'World') {
  12. console.log(x, y);
  13. }
  14. log('Hello');
  15. log('Hello', 'China');
  16. log('Hello', false);
  1. // 实例1
  2. function Point(x = 0, y = 0) {
  3. this.x = x;
  4. this.y = y;
  5. }
  6. var p = new Point();
  7. console.log(p);
  8. // 与解构赋值默认值结合使用
  9. function foo({ x, y = 5 }) {
  10. console.log(x, y);
  11. }
  12. foo({});
  13. foo({ x: 1 });
  14. foo({ x: 1, y: 2 });
  15. foo();

rest 参数,用于获取多余的参数,形式为(“…变量名”)

  1. // demo1
  2. function add(...values) {
  3. let sum = 0;
  4. for (var val of values) {
  5. sum += val;
  6. }
  7. return sum;
  8. }
  9. add(2, 3, 4, 5);
  1. // demo2 rest代替arguments
  2. // 数组排序 arguments变量的写法
  3. function sortNumbers1() {
  4. return Array.prototype.slice.call(arguments).sort();
  5. }
  6. // 数组排序 rest参数的写法
  7. const sortNumbers2 = (...numbers) => numbers.sort();
  1. // demo3 替代数组的apply方法
  2. function f(x, y, z) {
  3. //...
  4. }
  5. var args = [0, 1, 2];
  6. f.apply(null, args);
  7. //ES6的写法
  8. function f1(x, y, z) {
  9. //...
  10. }
  11. var args1 = [1, 2, 3];
  12. f1(...args1);
  1. // demo4 数组合并
  2. var arr1 = [0, 2, 4];
  3. var arr2 = [1, 3, 4];
  4. Array.prototype.push.apply(arr1, arr2);
  5. // ES6的写法
  6. var arr3 = [9, 8, 7];
  7. var arr4 = [6, 5, 4];
  8. arr3.push(...arr4);

箭头函数

  1. const func = () => {
  2. console.log('test');
  3. };
  4. setTimeout(() => {}, 1000);