溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

在JS中避免過多的使用IF語句方法有哪些

發(fā)布時(shí)間:2021-11-04 16:18:02 來源:億速云 閱讀:103 作者:iii 欄目:web開發(fā)

本篇內(nèi)容主要講解“在JS中避免過多的使用IF語句方法有哪些”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“在JS中避免過多的使用IF語句方法有哪些”吧!

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

(1) 事例1

帶有IF的代碼:

function saveCustomer(customer) {   if (isCustomerValid(customer)) {     database.save(customer)   } else {     alert('customer is invalid')   } }

重構(gòu)后代碼:

function saveCustomer(customer) {   return isCustomerValid(customer)     ? database.save(customer)     : alert('customer is invalid') }

使用 ES6

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

(2) 事例2

帶有IF的代碼:

 function customerValidation(customer) {    if (!customer.email) {      return error('email is require')    } else if (!customer.login) {     return error('login is required')    } else if (!customer.name) {      return error('name is required')    } else {      return customer   } }

重構(gòu)后代碼:

const customercustomerValidation = customer =>   !customer.email   ? error('email is required')   : !customer.login ? error('login is required')   : !customer.name  ? error('name is required')                     : customer

(3) 事例3

帶有IF的代碼:

 function getEventTarget(evt) {      if (!evt) {          evt = window.event;      }      if (!evt) {          return;      }      const target;      if (evt.target) {         target = evt.target;     } else {         target = evt.srcElement;     }     return target; }

重構(gòu)后代碼:

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

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

(1) 事例1

帶有IF的代碼:

 const isOnline = true;  const makeReservation= ()=>{};  const user = {      name:'Damian',      age:32,      dni:33295000  };    if (isOnline){     makeReservation(user); }

重構(gòu)后代碼:

const isOnline = true; const makeReservation= ()=>{}; const user = {     name:'Damian',     age:32,     dni:33295000 };  isOnline&&makeReservation(user);

(2) 事例2

帶有IF的代碼:

 const active = true;  const loan = {      uuid:123456,      ammount:10,      requestedBy:'rick'  };    const sendMoney = ()=>{};   if (active&&loan){     sendMoney(); }

重構(gòu)后代碼:

const active = true; const loan = {     uuid:123456,     ammount:10,     requestedBy:'rick' };  const sendMoney = ()=>{};  ctive && loan && sendMoney();

3. 函數(shù)委托

事例1

帶有IF的代碼:

function itemDropped(item, location) {     if (!item) {         return false;     } else if (outOfBounds(location) {         var error = outOfBounds;         server.notify(item, error);         items.resetAll();         return false;     } else {        animateCanvas();        server.notify(item, location);        return true;    }

重構(gòu)后代碼:

 function itemDropped(item, location) {      const dropOut = function() {          server.notify(item, outOfBounds);         items.resetAll();          return false;      }       const dropIn = function() {          server.notify(item, location);         animateCanvas();         return true;     }      return !!item && (outOfBounds(location) ? dropOut() : dropIn()); }

4. 非分支策略

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

(1) 事例1

帶有switch的代碼:

 switch(breed){      case 'border':        return 'Border Collies are good boys and girls.';        break;        case 'pitbull':        return 'Pit Bulls are good boys and girls.';        break;        case 'german':        return 'German Shepherds are good boys and girls.';       break;     default:       return 'Im default' }

重構(gòu)后代碼:

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

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

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

帶有IF的代碼:

 const calc = {      run: function(op, n1, n2) {          const result;          if (op == "add") {              result = n1 + n2;          } else if (op == "sub" ) {              result = n1 - n2;          } else if (op == "mult" ) {              result = n1 * n2;         } else if (op == "div" ) {             result = n1 / n2;         }         return result;     } }  calc.run("sub", 5, 3); //2

重構(gòu)后代碼:

 const calc = {      add : function(a,b) {          return a + b;      },      sub : function(a,b) {          return a - b;      },      mult : function(a,b) {          return a * b;     },     div : function(a,b) {         return a / b;     },     run: function(fn, a, b) {         return fn && fn(a,b);     } }  calc.run(calc.mult, 7, 4); //28

6. 多態(tài)性

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

帶有IF的代碼:

 const bob = {    name:'Bob',    salary:1000,    job_type:'DEVELOPER'  };    const mary = {    name:'Mary',    salary:1000,   job_type:'QA' };  const calc = (person) =>{      if (people.job_type==='DEVELOPER')         return person.salary+9000*0.10;      if (people.job_type==='QA')         return person.salary+1000*0.60; }  console.log('Salary',calc(bob)); console.log('Salary',calc(mary));

重構(gòu)后代碼:

 const qaSalary  = (base) => base+9000*0.10;  const devSalary = (base) => base+1000*0.60;    //Add function to the object.  const bob = {    name:'Bob',    salary:1000,    job_type:'DEVELOPER',    calc: devSalary };  const mary = {   name:'Mary',   salary:1000,   job_type:'QA',   calc: qaSalary };  console.log('Salary',bob.calc(bob.salary)); console.log('Salary',mary.calc(mary.salary));

到此,相信大家對(duì)“在JS中避免過多的使用IF語句方法有哪些”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

js
AI