继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

ES6一些功能的最优语法

前端绅士
关注TA
已关注
手记 54
粉丝 1.6万
获赞 893

以下是从头撸JavaScript官方文档整理,自己有点陌生或觉得对新人有用的内容,不定期更新。

检测属性值

const has = Object.prototype.hasOwnProperty
console.log(has.call(object, key))

合并对象

const original = { a: 1, b: 2 }
const copy = { ...original, c: 3 } // copy => { a: 1, b: 2, c: 3 }

const { a, ...noA } = copy // 声明并获取noA:{b: 2, c: 3}

拷贝数组

const itemsCopy = [...items]

类数组对象转化成数组

const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 }
const arr = Array.from(arrLike);

关于Array.from,请看我另一篇文章:《强大的Array.from()函数,简介与调试》

解构

function getFullName({ firstName, lastName }) {
  return `${firstName} ${lastName}`
}

const arr = [1, 2, 3, 4]
const [first, second] = arr

function processInput(input) {
  // todo...
  return { left, right, top, bottom }
}

const { left, top } = processInput(input)

字符串字面量

const name = 'Capt. Janeway'

就是告诉你优先使用单引号,不涉及计算就别闲着蛋疼用斜箭头

函数声明

const short = function longUniqueMoreDescriptiveLexicalFoo() {

}

之前有提过函数的提升,这样做就是避免提升,提高代码可读性。关于函数提升:《JavaScript终极BOSS》

非功能模块不要声明函数

let test;
if (currentUser) {
  test = () => {
    console.log('Yup.');
  }
}

非功能模块:if,for,while等。

如果非要用,请使用箭头函数。

arguments

function concatenateAll(...args) {
  return args.join('');
}

class替换prototype

// bad
function Queue(contents = []) {
  this.queue = [...contents]
}
Queue.prototype.pop = function () {
  const value = this.queue[0]
  this.queue.splice(0, 1)
  return value
}

// good
class Queue {
  constructor(contents = []) {
    this.queue = [...contents]
  }
  pop() {
    const value = this.queue[0];
    this.queue.splice(0, 1)
    return value
  }
}

class返回this的链式调用

class Jedi {
  jump() {
    this.jumping = true
    return this
  }

  setHeight(height) {
    this.height = height
    return this
  }
}

const luke = new Jedi()

luke.jump()
  .setHeight(20)

尽量使用专门的函数

const numbers = [1, 2, 3, 4, 5]

const sum = numbers.reduce((total, num) => total + num, 0)
sum === 15

const increasedByOne = numbers.map(num => num + 1)

变量逐个声明

const goSportsTeam = true
const items = getItems()
let dragonball
let i
let length

不要使用逗号一口气声明的原因是逐行声明方便调试。

自增自减

num += 1
num -= 1

减少++或--的使用,除非必要,如for。

case单句需要大括号

switch (foo) {
  case 1: {
    let x = 1
    break
  }
  case 2: {
    const y = 2
    break
  }
  case 3: {
    function f() {
      // ...
    }
    break
  }
  case 4:
    bar()
    break
  default: {
    class C {}
  }
}

if的大括号

if (test) return false

if (test) {
  return false
}

两者都可以,个人喜欢第一种,可单行的句子才行。

if语句衔接

// bad
if (test) {
  thing1()
  thing2()
}
else {
  thing3()
}

// good
if (test) {
  thing1()
  thing2()
} else {
  thing3()
}

没必要换行。

单行注释的位置

// bad
const active = true;  // is current tab

// good
// is current tab
const active = true;

咳咳,上面我的注释都可以理解成反面教材了。

缩进2个空格

function baz() {
∙∙let name;
}

好了好了,同学们不要抬杠了,听官方的吧。

function括号与大括号

// bad
function test(){
  console.log('test');
}

// good
function test() {
  console.log('test');
}

这是我不用ESLint原因,太坑,老是把我函数名与括号之间加上空格。

对象键值两边的空格

// bad
const foo = {clark: 'kent'};

// good
const foo = { clark: 'kent' };

常见的类型转换

const totalScore = String(this.reviewScore)
const val = Number(inputValue)
const hasAge = !!age

检测无效数字先行转换

// bad
isNaN('1.2'); // false
isNaN('1.2.3'); // true

// good
Number.isNaN('1.2.3'); // false
Number.isNaN(Number('1.2.3')); // true

不知道这些有没有你不知道的呢?


喜欢的话请关注一波,定期更新技术文章,满满的都是干货。

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP