ES6 开发者的 7 个黑客技巧

价值 | 思考 | 共鸣

640?wx_fmt=gif&wxfrom=5&wx_lazy=1

简评:ES6(ECMAScript2015)实际上是一种新的 JavaScript 规范,包含了一些很棒的新特性,可以更加方便地实现很多复杂的操作。

简评: 先看一下 ES6 的新特性:

  • Default Parameters in ES6(默认参数)

  • Template Literals in ES6(模板文本)

  • Multi-line Strings in ES6(多行字符串)

  • Destructuring Assignment in ES6(解构赋值)

  • Enhanced Object Literals in ES6(增强的对象文本)

  • Arrow Functions in ES6(箭头函数)

  • Promises in ES6

  • Block-Scoped Constructs Let and Const(块作用域构造 Let and Const)

  • Classes in ES6(类)

  • Modules in ES6(模块)

ES6 开发者的 7 个黑客技巧_第1张图片

Hack #1: Swap variables 交换变量

使用 Array Destructuring 交换值

 
   
  1. let a = 'world', b = 'hello'

  2. [a, b] = [b, a]

  3. console.log(a) // -> hello

  4. console.log(b) // -> world

  5. // Yes, it's magic

Hack #2 : Async/Await with Destructuring

下面这段代码可以同时发起两个异步请求,把请求结果分别附到 user 和 account 中

 
   
  1. const [user, account] = await Promise.all([

  2.  fetch('/user'),

  3.  fetch('/account')

  4. ])

Hack #3 :  Debugging

 
   
  1. const a = 5, b = 6, c = 7

  2. console.log({ a, b, c })

  3. // outputs this nice object:

  4. // {

  5. //    a: 5,

  6. //    b: 6,

  7. //    c: 7

  8. // }

Hack #4 : One liners

更紧凑的数组操作语法

 
   
  1. // Find max value

  2. const max = (arr) => Math.max(...arr);

  3. max([123, 321, 32]) // outputs: 321

  4. // Sum array

  5. const sum = (arr) => arr.reduce((a, b) => (a + b), 0)

  6. sum([1, 2, 3, 4]) // output: 10

Hack #5 :  Array concatenation

展开运算符可以用来代替 concat

ES6 开发者的 7 个黑客技巧_第2张图片

Hack #6 : Cloning

 
   
  1. const obj = { ...oldObj }

  2. const arr = [ ...oldArr ]

Hack #7 : Named parameters 参数命名

ES6 开发者的 7 个黑客技巧_第3张图片



英文原文:7 Hacks for ES6 Developers 

ES6 开发者的 7 个黑客技巧_第4张图片

▼点击阅读原文获取文中链接


你可能感兴趣的:(ES6 开发者的 7 个黑客技巧)