让你的JS代码更加简短&优美

原文地址:improve your JavaScript
Tip: 基于ES6编写

1.三元运算符
before:

const x = 20;
let big;

if (x > 10) {
    big = true;
} else {
    big = false;
}

after:

const big = x > 10 ? true : false;

more:

const big = x > 10 ? " greater 10" : x < 5 ? "less 5" : "between 5 and 10";

2.短路判断
before:

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     let variable2 = variable1;
}

after:

const variable2 = variable1  || 'new';

3.变量声明
before:

let x;
let y;
let z = 3;

after:

let x, y, z=3;

4.如果存在
before:

if (likeJavaScript === true)

after:

if (likeJavaScript)

5.循环
before:

for (let i = 0; i < allImgs.length; i++)

after:

for (let index in allImgs)

6.变量通过短路判断赋值
before:

let dbHost;
if (process.env.DB_HOST) {
  dbHost = process.env.DB_HOST;
} else {
  dbHost = 'localhost';
}

after:

const dbHost = process.env.DB_HOST || 'localhost';

7.十进制基数指数
before:

for (let i = 0; i < 10000; i++) {}

after:

for (let i = 0; i < 1e7; i++) {}

8.对象属性
before:

const obj = { x:x, y:y };

after:

const obj = { x, y };

9.箭头函数
before:

function sayHello(name) {
  console.log('Hello', name);
}

setTimeout(function() {
  console.log('Loaded')
}, 2000);

list.forEach(function(item) {
  console.log(item);
});

after:

sayHello = name => console.log('Hello', name);

setTimeout(() => console.log('Loaded'), 2000);

list.forEach(item => console.log(item));

10.函数返回值
before:

function calcCircumference(diameter) {
  return Math.PI * diameter
}

after:

calcCircumference = diameter => (
  Math.PI * diameter;
)

11.默认参数
before:

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}

after:

volume = (l, w = 3, h = 4 ) => (l * w * h);

12.模板
before:

const welcome = 'You have logged in as ' + first + ' ' + last + '.'

const db = 'http://' + host + ':' + port + '/' + database;

after:

const welcome = `You have logged in as ${first} ${last}`;

const db = `http://${host}:${port}/${database}`;

13.在使用类似react的第三方库的时候
before:

const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');

const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;

after:

import { observable, action, runInAction } from 'mobx';
const { store, form, loading, errors, entity } = this.props;

14.多行字符串
before:

const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'
    + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'
    + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'
    + 'veniam, quis nostrud exercitation ullamco laboris\n\t'
    + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'
    + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'

after:

const lorem = `Lorem ipsum dolor sit amet, consectetur
    adipisicing elit, sed do eiusmod tempor incididunt
    ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris
    nisi ut aliquip ex ea commodo consequat. Duis aute
    irure dolor in reprehenderit in voluptate velit esse.`

15.拓展运算符
before:

// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()

after:

// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];

还可以在数组的任意位置插入:

const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];

17.Array.find
before:

const pets = [
  { type: 'Dog', name: 'Max'},
  { type: 'Cat', name: 'Karl'},
  { type: 'Dog', name: 'Tommy'},
]

function findDog(name) {
  for(let i = 0; i<pets.length; ++i) {
    if(pets[i].type === 'Dog' && pets[i].name === name) {
      return pets[i];
    }
  }
}

after:

pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

18.Object[key]
before:

function validate(values) {
  if(!values.first)
    return false;
  if(!values.last)
    return false;
  return true;
}

console.log(validate({first:'Bruce',last:'Wayne'})); // true

after:

// object validation rules
const schema = {
  first: {
    required:true
  },
  last: {
    required:true
  }
}

// universal validation function
const validate = (schema, values) => {
  for(field in schema) {
    if(schema[field].required) {
      if(!values[field]) {
        return false;
      }
    }
  }
  return true;
}


console.log(validate(schema, {first:'Bruce'})); // false
console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true

19.双位不定式
before:

Math.floor(4.9) === 4  //true

after:

~~4.9 === 4  //true

在原文的评论当中还有很多类似的例子,在这里就不一一列举了.有兴趣的可以查看原文

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 把《C++ Primer》[https://book.douban.com/subject/25708312...
    尤汐Yogy阅读 9,542评论 1 51
  • C++运算符重载-上篇 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符和二元逻辑运算符4...
    Haley_2013阅读 2,326评论 0 51
  • 生活应该向前看的,只有把自己从过去中解放出来,你前面的脚下才有路。 大舍大得,小舍小得,不舍不得。生活是没有捷径的...
    洋氵羊阅读 239评论 0 0
  • 公休两天,加上夜班的休息,一下子竟腾出来六七天的休息,于是我选择回家跟爸爸妈妈团聚。 一年来,我回家要么在春节,要...
    真爱521阅读 238评论 0 0
  • 最近一年多来,越来越觉得孤单。有的朋友是仅限于上班期间的,在一起工作时大家走的很近,推心置腹的那种,但下班后...
    一人行走阅读 292评论 0 0