原文地址:improve your JavaScript
Tip: 基于ES6編寫
1.三元運(yùn)算符
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.循環(huán)
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.十進(jìn)制基數(shù)指數(shù)
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.箭頭函數(shù)
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.函數(shù)返回值
before:
function calcCircumference(diameter) {
return Math.PI * diameter
}
after:
calcCircumference = diameter => (
Math.PI * diameter;
)
11.默認(rèn)參數(shù)
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.拓展運(yùn)算符
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];
還可以在數(shù)組的任意位置插入:
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
在原文的評論當(dāng)中還有很多類似的例子,在這里就不一一列舉了.有興趣的可以查看原文