當想寫if...else語句時,使用三元操做符來代替。javascript
const x = 20; let answer; if (x > 10) { answer = 'is greater'; } else { answer = 'is lesser'; }
簡寫:const answer = x > 10 ? 'is greater' : 'is lesser';
java
也能夠嵌套if語句:const big = x > 10 ? " greater 10" : x
web
當給一個變量分配另外一個值時,想肯定源始值不是null,undefined或空值。能夠寫撰寫一個多重條件的if語句。數組
if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1; }
或者可使用短路求值方法:const variable2 = variable1 || 'new';
框架
let x; let y; let z = 3;
簡寫方法:let x, y, z=3;
less
if (likeJavaScript === true)
函數
簡寫:if (likeJavaScript)
ui
只有likeJavaScript是真值時,兩者語句才相等this
若是判斷值不是真值,則能夠這樣:翻譯
let a; if ( a !== true ) { // do something... }
簡寫:
let a; if ( !a ) { // do something... }
for (let i = 0; i < allImgs.length; i++)
簡寫:for (let index in allImgs)
也可使用Array.forEach:
function logArrayElements(element, index, array) { console.log("a[" + index + "] = " + element); } [2, 5, 9].forEach(logArrayElements); // logs: // a[0] = 2 // a[1] = 5 // a[2] = 9
給一個變量分配的值是經過判斷其值是否爲null或undefined,則能夠:
let dbHost; if (process.env.DB_HOST) { dbHost = process.env.DB_HOST; } else { dbHost = 'localhost'; }
簡寫:const dbHost = process.env.DB_HOST || 'localhost';
當須要寫數字帶有不少零時(如10000000),能夠採用指數(1e7)來代替這個數字:for (let i = 0; i < 10000; i++) {}
簡寫:
for (let i = 0; i < 1e7; i++) {} // 下面都是返回true 1e0 === 1; 1e1 === 10; 1e2 === 100; 1e3 === 1000; 1e4 === 10000; 1e5 === 100000;
若是屬性名與key名相同,則能夠採用ES6的方法:const obj = { x:x, y:y };
簡寫:const obj = { x, y };
傳統函數編寫方法很容易讓人理解和編寫,可是當嵌套在另外一個函數中,則這些優點就蕩然無存。
function sayHello(name) { console.log('Hello', name); } setTimeout(function() { console.log('Loaded') }, 2000); list.forEach(function(item) { console.log(item); });
簡寫:
sayHello = name => console.log('Hello', name); setTimeout(() => console.log('Loaded'), 2000); list.forEach(item => console.log(item));
常常使用return語句來返回函數最終結果,一個單獨語句的箭頭函數能隱式返回其值(函數必須省略{}爲了省略return關鍵字)
爲返回多行語句(例如對象字面表達式),則須要使用()包圍函數體。
function calcCircumference(diameter) { return Math.PI * diameter } var func = function func() { return { foo: 1 }; };
簡寫:
calcCircumference = diameter => ( Math.PI * diameter; ) var func = () => ({ foo: 1 });
爲了給函數中參數傳遞默認值,一般使用if語句來編寫,可是使用ES6定義默認值,則會很簡潔:
function volume(l, w, h) { if (w === undefined) w = 3; if (h === undefined) h = 4; return l * w * h; }
簡寫:
volume = (l, w = 3, h = 4 ) => (l * w * h); volume(2) //output: 24
傳統的JavaScript語言,輸出模板一般是這樣寫的。
const welcome = 'You have logged in as ' + first + ' ' + last + '.' const db = 'http://' + host + ':' + port + '/' + database;
ES6可使用反引號和${}簡寫:
const welcome = `You have logged in as ${first} ${last}`; const db = `http://${host}:${port}/${database}`;
在web框架中,常常須要從組件和API之間來回傳遞數組或對象字面形式的數據,而後須要解構它
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;
簡寫:
import { observable, action, runInAction } from 'mobx'; const { store, form, loading, errors, entity } = this.props;
也能夠分配變量名:
const { store, form, loading, errors, entity:contact } = this.props; //最後一個變量名爲contact
須要輸出多行字符串,須要使用+來拼接:
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'
使用反引號,則能夠達到簡寫做用:
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.`
擴展運算符有幾種用例讓JavaScript代碼更加有效使用,能夠用來代替某個數組函數。
// 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()
簡寫:
// 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];
不像concat()函數,可使用擴展運算符來在一個數組中任意處插入另外一個數組。
const odd = [1, 3, 5 ]; const nums = [2, ...odd, 4 , 6];
也可使用擴展運算符解構:
const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 }; console.log(a) // 1 console.log(b) // 2 console.log(z) // { c: 3, d: 4 }
JavaScript中若是沒有向函數參數傳遞值,則參數爲undefined。爲了加強參數賦值,可使用if語句來拋出異常,或使用強制參數簡寫方法。
function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter!'); } return bar; }
簡寫:
mandatory = () => { throw new Error('Missing parameter!'); } foo = (bar = mandatory()) => { return bar; }
想從數組中查找某個值,則須要循環。在ES6中,find()函數能實現一樣效果。
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]; } } }
簡寫:
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy'); console.log(pet); // { type: 'Dog', name: 'Tommy' }
考慮一個驗證函數
function validate(values) { if(!values.first) return false; if(!values.last) return false; return true; } console.log(validate({first:'Bruce',last:'Wayne'})); // true
假設當須要不一樣域和規則來驗證,可否編寫一個通用函數在運行時確認?
// 對象驗證規則 const schema = { first: { required:true }, last: { required:true } } // 通用驗證函數 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
如今能夠有適用於各類狀況的驗證函數,不須要爲了每一個而編寫自定義驗證函數了
有一個有效用例用於雙重非運算操做符。能夠用來代替Math.floor(),其優點在於運行更快,能夠閱讀此文章瞭解更多位運算。Math.floor(4.9) === 4 //true
簡寫:~~4.9 === 4 //true
本文翻譯於SitePoint:https://www.sitepoint.com/sho...