ES6 部分未用语法(转载)

172 阅读1分钟

1. 数组去重

// 例子1

[...new Set(array)]


2. 动态属性

// 例子2

const x = {
  ['a' + '_' + 'b']: 'z'
}

console.log(x.a_b); // z


3. finally

// 例子3

fetch('file.json')
.then(data => data.json())
.catch(error => console.error(error))
.finally(() => console.log('finished'));

4. 编辑表单时的拷贝

// 例子4

function fetch() {
  try {
    const data = JSON.parse(JSON.stringify(data))
  } catch (err) {
    console.log(err)
  }
};

5. "async 地狱"

// 例子5

// bad
(async () => {
  const getList = await getList();
  const getAnotherList = await getAnotherList();
})();

// good
(async () => {
  const listPromise = getList();
  const anotherListPromise = getAnotherList();
  await listPromise;
  await anotherListPromise;
})();

// good
(async () => {
  Promise.all([getList(), getAnotherList()]).then(...);
})();


6. 调用参数

// 例子6

// bad
Math.max.apply(null, [14, 3, 77])

// good
Math.max(...[14, 3, 77])
// 等同于
Math.max(14, 3, 77);


7. 构建对象

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

// 例子 7
let [a, b, ...arr] = [1, 2, 3, 4, 5];

const { a, b, ...others } = { a: 1, b: 2, c: 3, d: 4, e: 5 };


8. 合并对象

// 例子 8

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


9. 双冒号运算符

// 例子 9

foo::bar;
// 等同于
bar.bind(foo);

foo::bar(...arguments);
// 等同于
bar.apply(foo, arguments);

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

// 例子 9

var method = obj::obj.foo;
// 等同于
var method = ::obj.foo;

let log = ::console.log;
// 等同于
var log = console.log.bind(console);


10. 变量重命名

// 例子 10
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
console.log(baz); // "aaa"


11. includes

// 例子 11

// bad
function test(fruit) {
  if (fruit == 'apple' || fruit == 'strawberry') {
    ...
  }
}

// good
function test(fruit) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  if (redFruits.includes(fruit)) {
    ...
  }
}


12. Babel

babeljs.io/docs/en/bab…


原作者:冴羽
链接:https://juejin.cn/post/6844903726201700365
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。