日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當(dāng)前位置:首頁(yè) > 科技  > 軟件

JS小知識(shí),使用這六個(gè)小技巧,避免過(guò)多的使用 IF 語(yǔ)句

來(lái)源: 責(zé)編: 時(shí)間:2024-02-01 12:51:47 213觀看
導(dǎo)讀這些優(yōu)化技巧將防止我們?cè)?JavaScript 中過(guò)多地使用 IF 語(yǔ)句最近在重構(gòu)我的代碼時(shí),我注意到早期的代碼使用了太多的 if 語(yǔ)句,達(dá)到了我以前從未見(jiàn)過(guò)的程度。這就是為什么我認(rèn)為分享這些可以幫助我們避免使用過(guò)多 if 語(yǔ)句

oAV28資訊網(wǎng)——每日最新資訊28at.com

這些優(yōu)化技巧將防止我們?cè)?JavaScript 中過(guò)多地使用 IF 語(yǔ)句oAV28資訊網(wǎng)——每日最新資訊28at.com

最近在重構(gòu)我的代碼時(shí),我注意到早期的代碼使用了太多的 if 語(yǔ)句,達(dá)到了我以前從未見(jiàn)過(guò)的程度。這就是為什么我認(rèn)為分享這些可以幫助我們避免使用過(guò)多 if 語(yǔ)句的簡(jiǎn)單技巧很重要。oAV28資訊網(wǎng)——每日最新資訊28at.com

接下來(lái)我們介紹 6 種使用 if 的方法。這不是抵制使用if的偏執(zhí),也不是不讓大家以后不要用IF了,而是換一種方式來(lái)思考我們的編碼思路。oAV28資訊網(wǎng)——每日最新資訊28at.com

1、條件運(yùn)算符

(1)例子1:

使用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 customerValidation = customer =>  !customer.email   ? error('email is required')  : !customer.login ? error('login is required')  : !customer.name  ? error('name is required')                    : customer

(2)例子2:

使用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) {  evt = 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 = ()=>{};active && loan && sendMoney();

3、Function Delegation

使用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、非分支策略

使用Case:

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ù)對(duì)象

我們知道在 JS 中函數(shù)是尤其重要,所以使用它,我們也可以將代碼拆分成一個(gè)函數(shù)對(duì)象。如下面一個(gè)改造示例oAV28資訊網(wǎng)——每日最新資訊28at.com

使用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)性是一個(gè)對(duì)象具有多種形式的能力。 OOP 中多態(tài)性最常見(jiàn)的用法是使用父類(lèi)引用來(lái)引用子類(lèi)對(duì)象。oAV28資訊網(wǎng)——每日最新資訊28at.com

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

結(jié)束

今天的分享就到這里,這6個(gè)小技巧,是不是很棒呢,你怎么看呢?oAV28資訊網(wǎng)——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-70464-0.htmlJS小知識(shí),使用這六個(gè)小技巧,避免過(guò)多的使用 IF 語(yǔ)句

聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com

上一篇: 18個(gè)JavaScript技巧:編寫(xiě)簡(jiǎn)潔高效的代碼

下一篇: 在 Create React App 中使用 TypeScript,你學(xué)會(huì)了嗎?

標(biāo)簽:
  • 熱門(mén)焦點(diǎn)
Top 主站蜘蛛池模板: 翁牛特旗| 木兰县| 泰来县| 收藏| 高雄市| 高阳县| 剑川县| 武强县| 抚顺市| 十堰市| 沙湾县| 蓝山县| 太白县| 休宁县| 始兴县| 周至县| 南汇区| 蓬安县| 潍坊市| 秭归县| 莱芜市| 乐山市| 牟定县| 大关县| 全州县| 通山县| 济源市| 福建省| 乌鲁木齐县| 开远市| 大丰市| 朝阳市| 新晃| 扎囊县| 合肥市| 梓潼县| 四平市| 天等县| 华安县| 五莲县| 万州区|