自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

這些優(yōu)化技巧可以避免我們?cè)?JS 中過(guò)多的使用 IF 語(yǔ)句

開(kāi)發(fā) 前端
接下來(lái)會(huì)介紹6種方式來(lái)代替 if 的使用,這樣做不是堅(jiān)決不使用 if 偏執(zhí)狂,而是換個(gè)方式思考我們的編碼思路。

最近在重構(gòu)代碼時(shí),我發(fā)現(xiàn)早期的代碼使用太多的 if 語(yǔ)句,其程度是我從未見(jiàn)過(guò)的。這就是為什么我認(rèn)為分享這些簡(jiǎn)單的技巧是非常重要的,這些技巧可以幫助我們避免過(guò)多的使用 if 語(yǔ)句。

接下來(lái)會(huì)介紹6種方式來(lái)代替 if 的使用,這樣做不是堅(jiān)決不使用 if 偏執(zhí)狂,而是換個(gè)方式思考我們的編碼思路。

[[322188]]

1. 三元運(yùn)算符

(1) 事例1

帶有IF的代碼:

  1. function saveCustomer(customer) { 
  2.   if (isCustomerValid(customer)) { 
  3.     database.save(customer) 
  4.   } else { 
  5.     alert('customer is invalid') 
  6.   } 

重構(gòu)后代碼:

  1. function saveCustomer(customer) { 
  2.   return isCustomerValid(customer) 
  3.     ? database.save(customer) 
  4.     : alert('customer is invalid') 
  5. }  

使用 ES6

  1. const saveCustomer = customer => 
  2.    isCustomerValid(customer)? 
  3.      database.save(customer) : alert('customer is invalid')     

(2) 事例2

帶有IF的代碼:

  1.  function customerValidation(customer) { 
  2.    if (!customer.email) { 
  3.      return error('email is require') 
  4.    } else if (!customer.login) { 
  5.     return error('login is required') 
  6.    } else if (!customer.name) { 
  7.      return error('name is required') 
  8.    } else { 
  9.      return customer 
  10.   } 

重構(gòu)后代碼:

  1. const customercustomerValidation = customer => 
  2.   !customer.email   ? error('email is required') 
  3.   : !customer.login ? error('login is required') 
  4.   : !customer.name  ? error('name is required') 
  5.                     : customer 

(3) 事例3

帶有IF的代碼:

  1.  function getEventTarget(evt) { 
  2.      if (!evt) { 
  3.          evt = window.event; 
  4.      } 
  5.      if (!evt) { 
  6.          return; 
  7.      } 
  8.      const target; 
  9.      if (evt.target) { 
  10.         target = evt.target; 
  11.     } else { 
  12.         target = evt.srcElement; 
  13.     } 
  14.     return target; 

重構(gòu)后代碼:

  1. function getEventTarget(evt) { 
  2.   evtevt = evt || window.event; 
  3.   return evt && (evt.target || evt.srcElement); 

2. 短路運(yùn)算符

(1) 事例1

帶有IF的代碼:

  1.  const isOnline = true
  2.  const makeReservation= ()=>{}; 
  3.  const user = { 
  4.      name:'Damian', 
  5.      age:32, 
  6.      dni:33295000 
  7.  }; 
  8.   
  9.  if (isOnline){ 
  10.     makeReservation(user); 

重構(gòu)后代碼:

  1. const isOnline = true
  2. const makeReservation= ()=>{}; 
  3. const user = { 
  4.     name:'Damian', 
  5.     age:32, 
  6.     dni:33295000 
  7. }; 
  8.  
  9. isOnline&&makeReservation(user); 

(2) 事例2

帶有IF的代碼:

  1.  const active = true
  2.  const loan = { 
  3.      uuid:123456, 
  4.      ammount:10, 
  5.      requestedBy:'rick' 
  6.  }; 
  7.   
  8.  const sendMoney = ()=>{}; 
  9.   
  10. if (active&&loan){ 
  11.     sendMoney(); 

重構(gòu)后代碼:

  1. const active = true
  2. const loan = { 
  3.     uuid:123456, 
  4.     ammount:10, 
  5.     requestedBy:'rick' 
  6. }; 
  7.  
  8. const sendMoney = ()=>{}; 
  9.  
  10. ctive && loan && sendMoney(); 

3. 函數(shù)委托

事例1

帶有IF的代碼:

  1. function itemDropped(item, location) { 
  2.     if (!item) { 
  3.         return false; 
  4.     } else if (outOfBounds(location) { 
  5.         var error = outOfBounds
  6.         server.notify(item, error); 
  7.         items.resetAll(); 
  8.         return false; 
  9.     } else { 
  10.        animateCanvas(); 
  11.        server.notify(item, location); 
  12.        return true; 
  13.    } 

重構(gòu)后代碼:

  1.  function itemDropped(item, location) { 
  2.      const dropOut = function() { 
  3.          server.notify(item, outOfBounds); 
  4.         items.resetAll(); 
  5.          return false; 
  6.      } 
  7.  
  8.      const dropIn = function() { 
  9.          server.notify(item, location); 
  10.         animateCanvas(); 
  11.         return true; 
  12.     } 
  13.  
  14.     return !!item && (outOfBounds(location) ? dropOut() : dropIn()); 

4. 非分支策略

此技巧嘗試避免使用switch語(yǔ)句,相反是用鍵/值創(chuàng)建一個(gè)映射并使用一個(gè)函數(shù)訪(fǎng)問(wèn)作為參數(shù)傳遞的鍵的值。

(1) 事例1

帶有switch的代碼:

  1.  switch(breed){ 
  2.      case 'border': 
  3.        return 'Border Collies are good boys and girls.'; 
  4.        break;   
  5.      case 'pitbull': 
  6.        return 'Pit Bulls are good boys and girls.'; 
  7.        break;   
  8.      case 'german': 
  9.        return 'German Shepherds are good boys and girls.'; 
  10.       break; 
  11.     default: 
  12.       return 'Im default' 

重構(gòu)后代碼:

  1. const dogSwitch = (breed) =>({ 
  2.   "border": "Border Collies are good boys and girls.", 
  3.   "pitbull": "Pit Bulls are good boys and girls.", 
  4.   "german": "German Shepherds are good boys and girls.",   
  5. })[breed]||'Im the default'; 
  6.  
  7.  
  8. dogSwitch("border xxx") 

5. 作為數(shù)據(jù)的函數(shù)

我們知道在JS中函數(shù)是第一個(gè)類(lèi),所以使用它我們可以把代碼分割成一個(gè)函數(shù)對(duì)象。

帶有IF的代碼:

  1.  const calc = { 
  2.      run: function(op, n1, n2) { 
  3.          const result; 
  4.          if (op == "add") { 
  5.              result = n1 + n2; 
  6.          } else if (op == "sub" ) { 
  7.              result = n1 - n2; 
  8.          } else if (op == "mult" ) { 
  9.              result = n1 * n2; 
  10.         } else if (op == "div" ) { 
  11.             result = n1 / n2; 
  12.         } 
  13.         return result; 
  14.     } 
  15.  
  16. calc.run("sub", 5, 3); //2 

重構(gòu)后代碼:

  1.  const calc = { 
  2.      add : function(a,b) { 
  3.          return a + b; 
  4.      }, 
  5.      sub : function(a,b) { 
  6.          return a - b; 
  7.      }, 
  8.      mult : function(a,b) { 
  9.          return a * b; 
  10.     }, 
  11.     div : function(a,b) { 
  12.         return a / b; 
  13.     }, 
  14.     run: function(fn, a, b) { 
  15.         return fn && fn(a,b); 
  16.     } 
  17.  
  18. calc.run(calc.mult, 7, 4); //28 

6. 多態(tài)性

多態(tài)性是對(duì)象具有多種形式的能力。OOP中多態(tài)性最常見(jiàn)的用法是使用父類(lèi)引用來(lái)引用子類(lèi)對(duì)象。

帶有IF的代碼:

  1.  const bob = { 
  2.    name:'Bob', 
  3.    salary:1000, 
  4.    job_type:'DEVELOPER' 
  5.  }; 
  6.   
  7.  const mary = { 
  8.    name:'Mary', 
  9.    salary:1000, 
  10.   job_type:'QA' 
  11. }; 
  12.  
  13. const calc = (person) =>
  14.  
  15.     if (people.job_type==='DEVELOPER') 
  16.         return person.salary+9000*0.10; 
  17.  
  18.     if (people.job_type==='QA') 
  19.         return person.salary+1000*0.60; 
  20.  
  21. console.log('Salary',calc(bob)); 
  22. console.log('Salary',calc(mary)); 

重構(gòu)后代碼:

  1.  const qaSalary  = (base) => base+9000*0.10; 
  2.  const devSalary = (base) => base+1000*0.60; 
  3.   
  4.  //Add function to the object. 
  5.  const bob = { 
  6.    name:'Bob', 
  7.    salary:1000, 
  8.    job_type:'DEVELOPER', 
  9.    calc: devSalary 
  10. }; 
  11.  
  12. const mary = { 
  13.   name:'Mary', 
  14.   salary:1000, 
  15.   job_type:'QA', 
  16.   calc: qaSalary 
  17. }; 
  18.  
  19. console.log('Salary',bob.calc(bob.salary)); 
  20. console.log('Salary',mary.calc(mary.salary)); 

 

責(zé)任編輯:趙寧寧 來(lái)源: 前端小智
相關(guān)推薦

2024-01-30 08:43:26

IF 語(yǔ)句JavaScripJS

2021-07-05 06:51:43

流程代碼結(jié)構(gòu)

2023-02-08 17:00:07

IF 語(yǔ)句技巧代碼

2020-09-07 11:17:05

云計(jì)算

2015-02-11 10:00:15

2018-10-14 15:52:46

MySQL數(shù)據(jù)清理數(shù)據(jù)庫(kù)

2010-09-07 13:50:41

SQL語(yǔ)句

2024-12-05 09:02:00

Pythonif?

2022-05-10 10:39:51

初創(chuàng)企業(yè)技術(shù)債務(wù)

2017-09-13 08:34:48

2019-02-12 15:00:32

Javascript命令式編程前端

2016-03-24 09:53:24

swiftguardios

2022-07-04 08:51:43

條件語(yǔ)句JavaScript

2024-10-11 08:46:18

2020-03-06 10:35:35

數(shù)據(jù)中心能耗能源

2018-12-24 12:40:03

大數(shù)據(jù)IT互聯(lián)網(wǎng)

2020-08-12 09:45:23

SQL優(yōu)化技巧

2011-07-11 10:34:40

編程技巧蘋(píng)果

2017-08-07 15:52:33

Oracleonnect by優(yōu)化

2018-04-10 14:36:18

數(shù)據(jù)庫(kù)MySQL優(yōu)化技巧
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)