省时省力的ES6

人一懒起来啊,简直是………上一次发文章都是两个月前了:guardsman:

这次就收集一些ES6中的HACK吧!讲真的(会不会是..)…掌握这些技巧。能让我们少写很多行代码哦twemoji-1f427

1. 变量交换

  1. let a = 'world', b = 'hello'
  2. [a, b] = [b, a]
  3. console.log(a) // -> hello
  4. console.log(b) // -> world
  5. // 双击666

2. 接收函数返回的多个结果

使用async/await,函数会把返回值放在一个数组中。使用数组解构后就可以把返回值直接赋给相应的变量。

  1. const [user, account] = await Promise.all([
  2. fetch('/user'),
  3. fetch('/account')
  4. ])

3. 字符串拼接

  1. let a = 'hello',
  2. b = 'world';
  3. let _string = `${a} ${b}`
  4. console.log(_string); // "hello world"

4. 函数参数默认值

  1. const notify = (msg, {type='info', timeout, close=true} = {}) => {
  2. // display notification
  3. console.log(msg, type, timeout, close)
  4. }
  5. notify('Hi!'); // Hi! info undefined true
  6. notify('Hi!', {type: 'error'}); // Hi! error undefined true
  7. notify('Hi!', {type: 'warn', close: false}); // Hi! warn undefined false

5. 数组

代码不多一行搞定

  1. // 最大值
  2. const max = (arr) => Math.max(...arr);
  3. max([1, 2, 3]) // outputs: 321
  4. // 求和
  5. const sum = (arr) => arr.reduce((a, b) => (a + b), 0)
  6. sum([1, 2, 3, 4]) // output: 10
  7. // 拷贝
  8. let array1 = [1, "3", { a: 1}, 666];
  9. let copyArray = [ ...array1 ];
  10. console.log(copyArray) // [1, "3", {…}, 666]
  11. // 数组连接
  12. const one = ['a', 'b', 'c']
  13. const two = ['d', 'e', 'f']
  14. const three = ['g', 'h', 'i']
  15. // Old way #1
  16. const result = one.concat(two, three)
  17. // Old way #2
  18. const result = [].concat(one, two, three)
  19. // New
  20. const result = [...one, ...two, ...three]

6. 去重

通过 Set 可以轻易的实现数组去重

  1. function dedupe(array) {
  2. return [...new Set(array)];
  3. }
  4. let noDupes = dedupe([1, 2, "a", "a", { obj1: 999}, 7, 3, 1], { obj1: 999});
  5. console.log(noDupes); // [1, 2, "a", { obj1: 999}, 7, 3]

通过数组创建 Set 会删除数组中的重复项,而spread运算符会将 Set 转换为 Array

7. 强制要求参数

  1. const throwIfMissing = () => {
  2. throw new Error('Missing parameter');
  3. }
  4. const func = (requiredParam = throwIfMissing()) => {
  5. // some implementation
  6. }

8. 删除对象中不需要参数

  1. let { boy1, boy2, ...others } = { boy1: "sunshine", boy2: "sunshine", girl1: "beautiful", girl2 "very beautiful", girl2 "very beautiful", girl2 "very very beautiful" };
  2. console.log(others) // { girl1: "beautiful", girl2: "very beautiful", girl2: "very beautiful", girl2: "very very beautiful"}

9. 动态属性名

  1. let name = "mael";
  2. let me = {
  3. [`my-name-is-${name}`]: name,
  4. age: 24
  5. };

10. for 循环

  1. let a = ['a', 'b', 'c', 'd' ];
  2. // ES6
  3. for ( var val of a ) {
  4. console.log( val );
  5. } // "a" "b" "c" "d"
  6. // ES5
  7. for ( var idx in a ) {
  8. console.log( idx );
  9. } // 0 1 2 3

11. 定义抽象基类

抽象基类是一种专门用于继承的类。它不能直接构建。主要用例是继承的类具有公共接口。但是,class 尚未利用abstract关键字来创建抽象基类,我们可以使用new.target来模拟。

  1. class Note {
  2. constructor() {
  3. if (new.target === Note) {
  4. throw new Error('Note cannot be directly constructed.')
  5. }
  6. }
  7. }
  8. class ColorNote extends Note {
  9. }
  10. let note = new Note(); // error!
  11. let colorNote = new ColorNote(); // ok

12. 定义惰性范围函数

我们可以使用 generators 来创建一个惰性函数

  1. function* range(start, count) {
  2. for (let delta = 0; delta < count; delta++) {
  3. yield start + delta;
  4. }
  5. }
  6. for (let teenageYear of range(13, 7)) {
  7. console.log(`Teenage angst @ ${teenageYear}!`);
  8. }

写于 2018年09月04日Javascript Web 2327

如非特别注明,文章皆为原创。

转载请注明出处: https://www.liayal.com/article/5b8dfc9c7368ac07250bd11a

记小栈小程序上线啦~搜索【记小栈】【点击扫码】体验

你不想说点啥么?
😀😃😄😁😆😅😂🤣☺️😊😇🙂🙃😉😌😍😘😗😙😚😋😜😝😛🤑🤗🤓😎🤡🤠😏😒😞😔😟😕🙁☹️😣😖😫😩😤😠😡😶😐😑😯😦😧😮😲😵😳😱😨😰😢😥🤤😭😓😪😴🙄🤔🤥😬🤐🤢🤧😷🤒🤕😈👿👹👺💩👻💀☠️👽👾🤖🎃😺😸😹😻😼😽🙀😿😾👐👐🏻👐🏼👐🏽👐🏾👐🏿🙌🙌🏻🙌🏼🙌🏽🙌🏾🙌🏿👏👏🏻👏🏼👏🏽👏🏾👏🏿🙏🙏🏻🙏🏼🙏🏽🙏🏾🙏🏿🤝👍👍🏻👍🏼👍🏽👍🏾👍🏿👎👎🏻👎🏼👎🏽👎🏾👎🏿👊👊🏻👊🏼👊🏽👊🏾👊🏿✊🏻✊🏼✊🏽✊🏾✊🏿

评论

记小栈09-11 2018
@admin: 动态属性名那块,不用模板字符串呀,直接 [] 即可,比如文中 [name] === [`${name}`]

当初想拼字符串来着

alsotang09-11 2018

去重那个例子,函数dedupe的参数数量在定义和调用时不一致。

admin09-11 2018

动态属性名那块,不用模板字符串呀,直接 [] 即可,比如文中 [name] === [`${name}`]