原文:19+ JavaScript Shorthand Coding Techniquesjavascript
使用三目運算符,能夠更簡潔地把if else寫成一行java
const x = 20; let answer; if (x > 10) { answer = 'greater than 10'; } else { answer = 'less than 10'; }
const answer = x > 10 ? 'greater than 10' : 'less than 10';
當你把一個變量的值賦給另外一個變量,若是你要求原變量不能是空或者未定義,你有一長一短兩種寫法數組
if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1; }
const variable2 = variable1 || 'new';
let x; let y; let z = 3;
寫成less
let x, y, z=3;
(譯者注:其實如今standard風格不推薦聲明簡寫)函數
if (likeJavaScript === true) //簡化爲 if (likeJavaScript)
注意:這兩個例子不嚴格相等,
likeJavaScript
還多是其餘「爲真」的值,參考這裏ui
let a; if ( a !== true ) { // do something... } //簡化爲 let a; if ( !a ) { // do something... }
for (let i = 0; i < allImgs.length; i++) //簡化爲 for (let index of allImgs) //譯者拓展,用於循環key,不推薦在數組使用 for (let index in allImgs)
其實就是第二點...this
可能你早就知道了,這是一個不用在末尾寫一堆0的方法。例如1e7表明1後面跟7個0,也就是十進制的1000000。lua
for (let i = 0; i < 1e7; i++) {} // All the below will evaluate to true 1e0 === 1; 1e1 === 10; 1e2 === 100; 1e3 === 1000; 1e4 === 10000; 1e5 === 100000;
ES6提供的方法讓你更簡單地建立對象字面量,若是屬性名和值同樣的話,你能夠以下縮寫code
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));
另外,注意箭頭函數裏的this和普通函數不一樣orm
function calcCircumference(diameter) { return Math.PI * diameter } // 簡化爲 calcCircumference = diameter => Math.PI * diameter
注意:這個狀況下返回的必須是一行語句,若是返回對象要加()
,多行語句仍是用{}
和return
吧
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
const welcome = 'You have logged in as ' + first + ' ' + last + '.' const db = 'http://' + host + ':' + port + '/' + database; // 簡化爲 const welcome = `You have logged in as ${first} ${last}`; const db = `http://${host}:${port}/${database}`;
引入一個組件以後你還要一個一個拆出來?如今不用了!
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;
JavaScriptconst 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.`
能夠代替一些數組操做,而且比數組操做更靈活
// 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 }
function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter!'); } return bar; } // 簡化爲 mandatory = () => { throw new Error('Missing parameter!'); } foo = (bar = mandatory()) => { return bar; }
你可能用for循環寫過一個find函數,可是ES6已經引入了這個新特性!
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' }
(譯者:find跟filter的區別是filter返回數組,find只返回找到的第一個)
你知道foo.bar
能夠寫成foo['bar']
嗎?固然,不是知道這種用法就該這麼用,可是這麼寫可讓你重用一些代碼。
如下是一個簡單的驗證函數
function validate(values) { if(!values.first) return false; if(!values.last) return false; return true; } console.log(validate({first:'Bruce',last:'Wayne'})); // true
這個函數完美地完成了他的任務,可是當你有不少表單須要驗證,並且格式和規則都不一樣的時候,你就須要一個通用的驗證函數了。
// 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
雙重按位非的效果等於Math.floor()
Math.floor(4.9) === 4 //true // 至關於 ~~4.9 === 4 //true
注意注意,這條確實不利於其餘人看懂,須要合做的項目勿用,用了記得加註釋
3 ** 3 === 3 * 3 * 3 //a ** b就是a的b次方,也不用調用Math的方法了