ES6 部分未用语法(转载)

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. 构建对象

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

// 例子 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…
bash

原做者:冴羽 连接:https://juejin.im/post/5bfe05505188252098022400 来源:掘金 著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。
相关文章
相关标签/搜索