12. 拓展运算符

1. arguments 转数组

  1. // 例子 12-1
  2.  
  3. // bad
  4. function sortNumbers() {
  5. return Array.prototype.slice.call(arguments).sort();
  6. }
  7.  
  8. // good
  9. const sortNumbers = (...numbers) => numbers.sort();

2. 调用参数

  1. // 例子 12-2
  2.  
  3. // bad
  4. Math.max.apply(null, [14, 3, 77])
  5.  
  6. // good
  7. Math.max(...[14, 3, 77])
  8. // 等同于
  9. Math.max(14, 3, 77);

3. 构建对象

剔除部分属性,将剩下的属性构建一个新的对象

  1. // 例子 12-3
  2. let [a, b, ...arr] = [1, 2, 3, 4, 5];
  3.  
  4. const { a, b, ...others } = { a: 1, b: 2, c: 3, d: 4, e: 5 };

有条件的构建对象

  1. // 例子 12-4
  2.  
  3. // bad
  4. function pick(data) {
  5. const { id, name, age} = data
  6.  
  7. const res = { guid: id }
  8.  
  9. if (name) {
  10. res.name = name
  11. }
  12. else if (age) {
  13. res.age = age
  14. }
  15.  
  16. return res
  17. }
  18.  
  19. // good
  20. function pick({id, name, age}) {
  21. return {
  22. guid: id,
  23. ...(name && {name}),
  24. ...(age && {age})
  25. }
  26. }

合并对象

  1. // 例子 12-5
  2.  
  3. let obj1 = { a: 1, b: 2,c: 3 }
  4. let obj2 = { b: 4, c: 5, d: 6}
  5. let merged = {...obj1, ...obj2};

4. React

将对象全部传入组件

  1. // 例子 12-6
  2.  
  3. const parmas = {value1: 1, value2: 2, value3: 3}
  4.  
  5. <Test {...parmas} />

13. 双冒号运算符

  1. // 例子 13-1
  2.  
  3. foo::bar;
  4. // 等同于
  5. bar.bind(foo);
  6.  
  7. foo::bar(...arguments);
  8. // 等同于
  9. bar.apply(foo, arguments);

如果双冒号左边为空,右边是一个对象的方法,则等于将该方法绑定在该对象上面。

  1. // 例子 13-2
  2.  
  3. var method = obj::obj.foo;
  4. // 等同于
  5. var method = ::obj.foo;
  6.  
  7. let log = ::console.log;
  8. // 等同于
  9. var log = console.log.bind(console);