當前位置:
首頁 > 最新 > 愛創課堂教程 19個JavaScript 常用的簡寫技術

愛創課堂教程 19個JavaScript 常用的簡寫技術

1.三元操作符

當想寫if...else語句時,使用三元操作符來代替。

const x = 20;let answer;if (x > 10) { answer = "is greater";} else { answer = "is lesser";}

簡寫:

const answer = x > 10 ? "is greater" : "is lesser";

也可以嵌套if語句:

const big = x > 10 ? " greater 10" : x

2.短路求值簡寫方式

當給一個變數分配另一個值時,想確定源始值不是null,undefined或空值。可以寫撰寫一個多重條件的if語句。

或者可以使用短路求值方法:

3.聲明變數簡寫方法

let x;let y;let z = 3;

簡寫方法:

let x, y, z=3;

4.if存在條件簡寫方法

if (likeJavaScript === true)

簡寫:

if (likeJavaScript)

只有likeJavaScript是真值時,二者語句才相等

如果判斷值不是真值,則可以這樣:

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

簡寫:

let a;if ( !a ) {// do something...}

5.JavaScript循環簡寫方法

for (let i = 0; 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

6.短路評價

給一個變數分配的值是通過判斷其值是否為null或undefined,則可以:

let dbHost;if (process.env.DB_HOST) { dbHost = process.env.DB_HOST;} else { dbHost = "localhost";}

簡寫:

const dbHost = process.env.DB_HOST || "localhost";

7.十進位指數

for (let i = 0; i

簡寫:

for (let i = 0; i

8.對象屬性簡寫

如果屬性名與key名相同,則可以採用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));

10.隱式返回值簡寫

經常使用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 });

11.默認參數值

為了給函數中參數傳遞默認值,通常使用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

12.模板字元串

傳統的JavaScript語言,輸出模板通常是這樣寫的。

const welcome = "You have logged in as " + first + " " + last + "."const db = "http://" + host + ":" + port + "/" + database;

ES6可以使用反引號和${}簡寫:

const welcome = `You have logged in as $ $`;const db = `http://$:$/$`;

13.解構賦值簡寫方法

在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

14.多行字元串簡寫

需要輸出多行字元串,需要使用+來拼接:

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

使用反引號,則可以達到簡寫作用:

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.擴展運算符簡寫

擴展運算符有幾種用例讓JavaScript代碼更加有效使用,可以用來代替某個數組函數。

// 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.強制參數簡寫

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

17.Array.find簡寫

想從數組中查找某個值,則需要循環。在ES6中,find()函數能實現同樣效果。

const pets = [ { type: "Dog", name: "Max"}, { type: "Cat", name: "Karl"}, { type: "Dog", name: "Tommy"},]function findDog(name) { for(let i = 0; i

簡寫:

pet = pets.find(pet => pet.type ==="Dog" && pet.name === "Tommy");console.log(pet); // { type: "Dog", name: "Tommy" }

18.Object[key]簡寫

考慮一個驗證函數

function validate(values) { if(!values.first) return false; if(!values.last) return false; return true;}console.log(validate()); // 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, )); // falseconsole.log(validate(schema, )); // true

現在可以有適用於各種情況的驗證函數,不需要為了每個而編寫自定義驗證函數了

19.雙重非位運算簡寫

有一個有效用例用於雙重非運算操作符。可以用來代替Math.floor(),其優勢在於運行更快。

Math.floor(4.9) === 4 //true

簡寫

~~4.9 === 4 //true

作者: yuyurenjie

源自:https://juejin.im/post/5948db9661ff4b006c061b2b

聲明:文章著作權歸作者所有,如有侵權,請聯繫小編刪除。


喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 愛創課堂 的精彩文章:

TAG:愛創課堂 |

您可能感興趣

『妄想課堂』Jack the Ripper
Class Report 課堂反饋
學在美本Study@American Colleges—大課堂篇
33oz class | vol 2 手工皮具小課堂
微軟公司收購課堂協作平台Chalkup,後者將整合入Microsoft Team教育產品中
Apple使用ClassKit教育框架,為教師,學生和管理員提供了更多的課堂力量
Swei英語小課堂「give cold shoulder」你需要一個「冷肩膀」嗎?
開學第一課:ray(anjeri)課堂
Garmin小課堂 如何使用Garmin pay移動支付功能?
Swei英語小課堂「add fuel to the fire」沒錯就是火上澆油
安仔課堂:滲透測試神器Cobalt Strike使用寶典!
「BigBang」「新聞」190719 崔勝鉉ins story暴風更新,崔老師的藝術課堂來了
索尼發力教育領域 Vision Exchange讓課堂真的「動」起來
Garmin小課堂 Garmin設備與手機連接配對最常見的5個問題
爐石英語小課堂第15期 「battlecry」 戰吼屬性
Dysonhair戴森頭髮課堂
戴爾Chromebook 5190教育系列亮相 USB-C和觸控筆能否讓它進入課堂?
華為mate10玩機課堂:詳解mate 10手機NFC功能,都認真學了!實用
朱老師信息技術課堂のPhotoshop一網打盡!
imToken 小課堂開課啦