12. 拓展运算符
1. arguments 转数组
- // 例子 12-1
- // bad
- function sortNumbers() {
- return Array.prototype.slice.call(arguments).sort();
- }
- // good
- const sortNumbers = (...numbers) => numbers.sort();
2. 调用参数
- // 例子 12-2
- // bad
- Math.max.apply(null, [14, 3, 77])
- // good
- Math.max(...[14, 3, 77])
- // 等同于
- Math.max(14, 3, 77);
3. 构建对象
剔除部分属性,将剩下的属性构建一个新的对象
- // 例子 12-3
- let [a, b, ...arr] = [1, 2, 3, 4, 5];
- const { a, b, ...others } = { a: 1, b: 2, c: 3, d: 4, e: 5 };
有条件的构建对象
- // 例子 12-4
- // bad
- function pick(data) {
- const { id, name, age} = data
- const res = { guid: id }
- if (name) {
- res.name = name
- }
- else if (age) {
- res.age = age
- }
- return res
- }
- // good
- function pick({id, name, age}) {
- return {
- guid: id,
- ...(name && {name}),
- ...(age && {age})
- }
- }
合并对象
- // 例子 12-5
- let obj1 = { a: 1, b: 2,c: 3 }
- let obj2 = { b: 4, c: 5, d: 6}
- let merged = {...obj1, ...obj2};
4. React
将对象全部传入组件
- // 例子 12-6
- const parmas = {value1: 1, value2: 2, value3: 3}
- <Test {...parmas} />
13. 双冒号运算符
- // 例子 13-1
- foo::bar;
- // 等同于
- bar.bind(foo);
- foo::bar(...arguments);
- // 等同于
- bar.apply(foo, arguments);
如果双冒号左边为空,右边是一个对象的方法,则等于将该方法绑定在该对象上面。
- // 例子 13-2
- var method = obj::obj.foo;
- // 等同于
- var method = ::obj.foo;
- let log = ::console.log;
- // 等同于
- var log = console.log.bind(console);