好程式設計師web前端教程分享JavaScript簡寫方法

好程式設計師IT發表於2019-10-14

今天好程式設計師web 前端教程為大家分享JavaScript 簡寫方法,小夥伴們快來看一看吧。

 

1. 三元運算子

 

當想寫if...else 語句時,使用三元運算子來代替。

 

  1. constx =20;

 

  1. let answer;

 

  1. if(x >10) {

 

  1. answer ='is greater';

 

  1. }else{

 

  1. answer ='is lesser';

 

7.  }

簡寫:

 

1.  constanswer = x >10?'is greater':'is lesser';

 

也可以巢狀if 語句:

 

1.  constbig = x >10?" greater 10": x

 

2. 短路求值簡寫方式

 

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

  1. if(variable1 !==null|| variable1 !==undefined|| variable1 !=='') {

 

  1. let variable2 = variable1;

 

3.  }

 

 

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

 

1.  constvariable2 = variable1  ||'new';

 

3. 宣告變數簡寫方法

 

1.  let x;

 

2.  let y;

 

3.  let z =3;

簡寫方法:

 

1.  letx, y, z=3;

 

4.if 存在條件簡寫方法

 

1.  if(likeJavaScript ===true)

 

簡寫:

 

1.  if(likeJavaScript)

 

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

 

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

 

1.  let a;

 

2.  if( a !==true) {

 

3.  // do something...

 

4.  }

簡寫:

 

1.  let a;

 

2.  if( !a ) {

 

3.  // do something...

 

4.  }

5.JavaScript 迴圈簡寫方法

 

1.  for(leti =0; i < allImgs.length; i++)

 

簡寫:for(letindexinallImgs) 也可以使用 Array.forEach

 

1.  functionlogArrayElements(element, index, array) {

 

2.    console.log("a["+ index +"] = "+ element);

 

3.  }

 

4.  [2,5,9].forEach(logArrayElements);

 

5.  // logs:

 

6.  // a[0] = 2

 

7.  // a[1] = 5

 

8.  // a[2] = 9

6. 短路評價

 

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

 

1.  let dbHost;

 

2.  if(process.env.DB_HOST) {

 

3.    dbHost = process.env.DB_HOST;

 

4.  }else{

 

5.    dbHost ='localhost';

 

6.  }

 

簡寫:

 

1.  constdbHost = process.env.DB_HOST ||'localhost';

 

7. 十進位制指數

 

當需要寫數字帶有很多零時(如10000000 ),可以採用指數( 1e7 )來代替這個數字: for(leti=0;i<10000;i++){} 簡寫:

 

1.  for(let i =0; i <1e7; i++) {}

 

2.  

 

3.  //下面都是返回true

 

4.  1e0===1;

 

5.  1e1===10;

 

6.  1e2===100;

 

7.  1e3===1000;

 

8.  1e4===10000;

 

9.  1e5===100000;

 

8. 物件屬性簡寫

 

如果屬性名與key 名相同,則可以採用 ES6 的方法:

 

1.  constobj = { x:x, y:y };

 

簡寫:

 

1.  constobj = { x, y };

 

9. 箭頭函式簡寫

 

傳統函式編寫方法很容易讓人理解和編寫,但是當巢狀在另一個函式中,則這些優勢就蕩然無存。

 

1.  functionsayHello(name) {

 

2.    console.log('Hello', name);

 

3.  }

 

4.  

 

5.  setTimeout(function() {

 

6.    console.log('Loaded')

 

7.  },2000);

 

8.  

 

9.  list.forEach(function(item) {

 

10.   console.log(item);

 

11. });

 

簡寫:

 

1.  sayHello = name => console.log('Hello', name);

 

2.  

 

3.  setTimeout(() => console.log('Loaded'),2000);

 

4.  

 

5.  list.forEach(item => console.log(item));

 

10. 隱式返回值簡寫

 

經常使用return 語句來返回函式最終結果,一個單獨語句的箭頭函式能隱式返回其值(函式必須省略 {} 為了省略 return 關鍵字)

 

為返回多行語句(例如物件字面表示式),則需要使用() 包圍函式體。

 

1.  functioncalcCircumference(diameter) {

 

2.    returnMath.PI * diameter

 

3.  }

 

4.  

 

5.  varfunc =functionfunc() {

 

6.    return{ foo:1};

 

7.  };

 

簡寫:

 

1.  calcCircumference = diameter => (

 

2.    Math.PI * diameter;

 

3.  )

 

4.  

 

5.  varfunc = () => ({ foo:1});

 

11. 預設引數值

 

為了給函式中引數傳遞預設值,通常使用if 語句來編寫,但是使用 ES6 定義預設值,則會很簡潔:

 

1.  functionvolume(l, w, h) {

 

2.    if(w ===undefined)

 

3.      w =3;

 

4.    if(h ===undefined)

 

5.      h =4;

 

6.    returnl * w * h;

 

7.  }

 

簡寫:

 

1.  volume = (l, w =3, h =4) => (l * w * h);

 

2.  

 

3.  volume(2)//output: 24

 

12. 模板字串

 

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

 

1.  constwelcome ='You have logged in as '+ first +' '+ last +'.'

 

2.  

 

3.  constdb ='

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

 

1.  constwelcome = `Youhave logged in as ${first} ${last}`;

 

2.  

 

3.  constdb = `{host}:${port}/${database}`;

 

13. 解構賦值簡寫方法

 

web 框架中,經常需要從元件和 API 之間來回傳遞陣列或物件字面形式的資料,然後需要解構它。

 

1.  constobservable = require('mobx/observable');

 

2.  constaction = require('mobx/action');

 

3.  construnInAction = require('mobx/runInAction');

 

4.  

 

5.  conststore =this.props.store;

 

6.  constform =this.props.form;

 

7.  constloading =this.props.loading;

 

8.  consterrors =this.props.errors;

 

9.  constentity =this.props.entity;

 

簡寫:

 

1.  import{ observable, action, runInAction } from'mobx';

 

2.  

 

3.  const{ store, form, loading, errors, entity } =this.props;

也可以分配變數名:

 

1.  const{ store, form, loading, errors, entity:contact } =this.props;

 

2.  //最後一個變數名為contact

 

14. 多行字串簡寫

 

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

 

1.  constlorem ='Lorem ipsum dolor sit amet, consectetur\n\t'

 

2.      +'adipisicing elit, sed do eiusmod tempor incididunt\n\t'

 

3.      +'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'

 

4.      +'veniam, quis nostrud exercitation ullamco laboris\n\t'

 

5.      +'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'

 

6.      +'irure dolor in reprehenderit in voluptate velit esse.\n\t'

 

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

 

1.  constlorem = `Loremipsum dolor sit amet, consectetur

 

2.      adipisicing elit, seddoeiusmod tempor incididunt

 

3.      ut labore et dolore magna aliqua.Utenim ad minim

 

4.      veniam, quis nostrud exercitation ullamco laboris

 

5.      nisi ut aliquip ex ea commodo consequat.Duisaute

 

6.      irure dolor in reprehenderit in voluptate velit esse.`

 

15. 擴充套件運算子簡寫

 

擴充套件運算子有幾種用例讓JavaScript 程式碼更加有效使用,可以用來代替某個陣列函式。

 

1.  // joining arrays

 

2.  constodd = [1,3,5];

 

3.  constnums = [2,4,6].concat(odd);

 

4.  

 

5.  // cloning arrays

 

6.  constarr = [1,2,3,4];

 

7.  constarr2 = arr.slice()

簡寫:

 

1.  // joining arrays

 

2.  constodd = [1,3,5];

 

3.  constnums = [2,4,6, ...odd];

 

4.  console.log(nums);// [ 2, 4, 6, 1, 3, 5 ]

 

5.  

 

6.  // cloning arrays

 

7.  constarr = [1,2,3,4];

 

8.  constarr2 = [...arr];

不像concat() 函式,可以使用擴充套件運算子來在一個陣列中任意處插入另一個陣列。

 

1.  constodd = [1,3,5];

 

2.  constnums = [2, ...odd,4,6];

也可以使用擴充套件運算子解構:

 

1.  const{ a, b, ...z } = { a:1, b:2, c:3, d:4};

 

2.  console.log(a)// 1

 

3.  console.log(b)// 2

 

4.  console.log(z)// { c: 3, d: 4 }

16. 強制引數簡寫

 

JavaScript 中如果沒有向函式引數傳遞值,則引數為 undefined 。為了增強引數賦值,可以使用 if 語句來丟擲異常,或使用強制引數簡寫方法。

1.  functionfoo(bar) {

 

2.    if(bar ===undefined) {

 

3.      thrownewError('Missing parameter!');

 

4.    }

 

5.    returnbar;

 

6.  }

 

簡寫:

1.  mandatory = () => {

 

2.    thrownewError('Missing parameter!');

 

3.  }

 

4.  

 

5.  foo = (bar = mandatory()) => {

 

6.    returnbar;

 

7.  }

 

17.Array.find 簡寫

 

想從陣列中查詢某個值,則需要迴圈。在ES6 中, find() 函式能實現同樣效果。

1.  constpets = [

 

2.    { type:'Dog', name:'Max'},

 

3.    { type:'Cat', name:'Karl'},

 

4.    { type:'Dog', name:'Tommy'},

 

5.  ]

 

6.  

 

7.  functionfindDog(name) {

 

8.    for(let i =0; i<pets.length; ++i) {

 

9.      if(pets[i].type ==='Dog'&& pets[i].name === name) {

 

10.       returnpets[i];

 

11.     }

 

12.   }

 

13. }

 

簡寫:

1.  pet = pets.find(pet => pet.type ==='Dog'&& pet.name ==='Tommy');

 

2.  console.log(pet);// { type: 'Dog', name: 'Tommy' }

 

18.Object[key] 簡寫

 

考慮一個驗證函式:

1.  functionvalidate(values) {

 

2.    if(!values.first)

 

3.      returnfalse;

 

4.    if(!values.last)

 

5.      returnfalse;

 

6.    returntrue;

 

7.  }

 

8.  

 

9.  console.log(validate({first:'Bruce',last:'Wayne'}));// true

 

假設當需要不同域和規則來驗證,能否編寫一個通用函式在執行時確認?

 

1.  //物件驗證規則

 

2.  constschema = {

 

3.    first: {

 

4.      required:true

 

5.    },

 

6.    last: {

 

7.      required:true

 

8.    }

 

9.  }

 

10. 

 

11. //通用驗證函式

 

12. constvalidate = (schema, values) => {

 

13.   for(field in schema) {

 

14.     if(schema[field].required) {

 

15.       if(!values[field]) {

 

16.         returnfalse;

 

17.       }

 

18.     }

 

19.   }

 

20.   returntrue;

 

21. }

 

22. 

 

23. console.log(validate(schema, {first:'Bruce'}));// false

 

24. console.log(validate(schema, {first:'Bruce',last:'Wayne'}));// true

 

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


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69913892/viewspace-2659923/,如需轉載,請註明出處,否則將追究法律責任。

相關文章