原文地址: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
在原文的评论当中还有很多类似的例子,在这里就不一一列举了.有兴趣的可以查看原文
网友评论