使用ES6优化代码

681 阅读1分钟

文章内容主要是参考阮一峰大神的ECMAScript 6 入门,省略各章节的概念介绍,总结使用ES6新语法如何优化代码。

未完,更新中......

1、扩展运算符spread(...)的使用

拷贝数组

// 写法一
const arrCopy = [...arr]

// 写法二
const [...arrCopy] = arr

将字符串转为数组

[...'Hello']

2、rest参数的使用

代替函数体内的arguments

rest参数之后不能再有其他参数,否则会报错

// 严格模式下,禁止使用arguments
// bad instance
function foo() {
    const args = Array.from(arguments)
    return args.join('')
}

// good instance
function foo(...args) {
    return args.join('')
}

3、使用默认值语法设置函数的参数

// bad instance
function bar(opt) {
    opt = opt || {}
}
// good instance
function bar(opt = {}) {
}

4、使用Symbol消除魔术字符串

魔术字符串指的是,在代码中多次出现,与代码形成强耦合的某一个具体的字符串或者数值

// 下面的“Triangle”就是魔法字符串
// "Triangle"多次出现,与代码形成“强耦合”,不利于将来的修改和维护。
function getArea(shape, {width, height}) {
    let area = 0;
    
    switch(shape) {
        case 'Triangle':
            area = 0.5 * width * height;
            break;
        // ...
    }
    
    return area;
}
getArea('Triangle', {width: 100, height: 50});

修改如下: 1、写成shapeType的triangle属性,消除耦合; 2、shapeType的triangle属性的值等于什么并不重要,只要确保不要与其他shapeType的属性值冲突即可,很适合用Symbol值

const shapeType = {
  triangle: Symbol()
}

function getArea(shape, {width, height}) {
  let area = 0;
  
  switch(shape) {
      case shapeType.triangle:
          area = 0.5 * width * height;
          break;
      // ...
  }
  
  return area;
}

5、使用(?.)链接判断运算符判断对象是否存在

ES2020引入了(?.)。在链式调用的时候,?.判断左侧对象是否存在,存在则继续往下,不存在,返回undefined。

// bad
const firstName = message.body.user.firstName || 'default'

// good
const firstName = (
    message 
    && message.body 
    && message.body.user
    && message.body.user.firstName) || 'default'

// best
const firstName = message?.body?.user?.firstName || 'default'

参考书籍

es6.ruanyifeng.com/