程序員總結:19種JavaScript高效縮寫法!

編程語言 JavaScript 程序員 Sed 孝道的重要性 孝道的重要性 2017-09-20

1 使用三目運算符

使用三目運算符,可以更簡潔地把if else寫成一行

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';

這篇文章共享之前我仍是要引薦下我自個的前端群:657137906,不論你是小白仍是大牛,小編我都挺期待,不定期共享乾貨,包含我自個整理的一份2017最新的前端材料和零根底入門教程,期待初學和進階中的小夥伴。

2 短路求值

當你把一個變量的值賦給另一個變量,如果你要求原變量不能是空或者未定義,你有一長一短兩種寫法

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

3 聲明變量的簡寫

let x;let y;let z = 3;

寫成

let x, y, z=3;

(譯者注:其實現在standard風格不推薦聲明簡寫)

4 if的簡寫

if (likeJavaScript === true)//簡化為if (likeJavaScript)

注意:這兩個例子不嚴格相等,likeJavaScript還可能是其他“為真”的值,參考這裡

let a;if ( a !== true ) {// do something...}//簡化為let a;if ( !a ) {// do something...}

5 JavaScript for循環簡寫

for (let i = 0; i < allImgs.length; i++)//簡化為for (let index of allImgs)//譯者拓展,用於循環key,不推薦在數組使用for (let index in allImgs)

6 短路求值

其實就是第二點...

7 十進制指數

可能你早就知道了,這是一個不用在末尾寫一堆0的方法。例如1e7代表1後面跟7個0,也就是十進制的1000000。

for (let i = 0; i < 1e7; i++) {}// All the below will evaluate to true1e0 === 1;1e1 === 10;1e2 === 100;1e3 === 1000;1e4 === 10000;1e5 === 100000;

8 對象屬性的縮寫

ES6提供的方法讓你更簡單地創建對象字面量,如果屬性名和值一樣的話,你可以如下縮寫

const obj = { x:x, y:y };// 等同於const obj = { x, y };

9 用箭頭函數讓代碼更簡潔

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和普通函數不同

10 箭頭函數的隱形return

function calcCircumference(diameter) { return Math.PI * diameter}// 簡化為calcCircumference = diameter => Math.PI * diameter

注意:這個情況下返回的必須是一行語句,如果返回對象要加(),多行語句還是用{}return

11 默認參數

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

12 反引號與模板字符串

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}`;

13 結構賦值

引入一個組件之後你還要一個一個拆出來?現在不用了!

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;

14 反引號與多行字符串

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.`

15 擴展運算符

可以代替一些數組操作,並且比數組操作更靈活

// joining arraysconst odd = [1, 3, 5];const nums = [2 ,4 , 6].concat(odd);// cloning arraysconst arr = [1, 2, 3, 4];const arr2 = arr.slice()
// joining arraysconst odd = [1, 3, 5 ];const nums = [2 ,4 , 6, ...odd];console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]// cloning arraysconst 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) // 1console.log(b) // 2console.log(z) // { c: 3, d: 4 }

16 強制參數(其實又跟11一樣)

function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter!'); } return bar;}// 簡化為mandatory = () => { throw new Error('Missing parameter!');}foo = (bar = mandatory()) => { return bar;}

17 Array.find

你可能用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只返回找到的第一個)

18 Object [key]

你知道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 rulesconst schema = { first: { required:true }, last: { required:true }}// universal validation functionconst validate = (schema, values) => { for(field in schema) { if(schema[field].required) { if(!values[field]) { return false; } } } return true;}console.log(validate(schema, {first:'Bruce'})); // falseconsole.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true

19 雙重按位非(這個挺實用)

雙重按位非的效果等於Math.floor()

Math.floor(4.9) === 4 //true// 相當於~~4.9 === 4 //true

20 由你來補充 ?

21 那我來補充一條吧!雙重*

3 ** 3 === 3 * 3 * 3//a ** b就是a的b次方,也不用調用Math的方法了

最後在說幾句:

  1. 厲害程序員相對於普通程序員的優勢在於:

  2. 遇到不懂的問題要及時提出來,也要多多自己去動手查百度,在不懂去請教他人,要懂得思考,分析,處理。

  3. 今天的分享到這裡寫完了,學習web前端的可以加我的群,每天分享對應的學習資料:657137906,歡迎初學和進階中的小夥伴。多寫多練。

如果想看到更加系統的文章和學習方法經驗可以關注我的微信公眾號:‘前端根據地’關注後回覆‘給我資料’可以領取一套完整的學習視頻

相關推薦

推薦中...