5

JS小知识,使用这六个小技巧,避免过多的使用 IF 语句

 7 months ago
source link: https://www.51cto.com/article/780654.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
e2d4d960060abace0dc809187866cd5cc080ab.png

这些优化技巧将防止我们在 JavaScript 中过多地使用 IF 语句

最近在重构我的代码时,我注意到早期的代码使用了太多的 if 语句,达到了我以前从未见过的程度。这就是为什么我认为分享这些可以帮助我们避免使用过多 if 语句的简单技巧很重要。

接下来我们介绍 6 种使用 if 的方法。这不是抵制使用if的偏执,也不是不让大家以后不要用IF了,而是换一种方式来思考我们的编码思路。

1、条件运算符

(1)例子1:

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

重构代码:

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

(2)例子2:

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

重构代码:

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

2、&&逻辑运算符

(1)例子1:

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

if (isOnline){
    makeReservation(user);
}

重构代码:

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

isOnline&&makeReservation(user);

(2)例子2:

const active = true;
const loan = {
    uuid:123456,
    ammount:10,
    requestedBy:'rick'
};

const sendMoney = ()=>{};

if (active&&loan){
    sendMoney();
}

重构代码:

const active = true;
const loan = {
    uuid:123456,
    ammount:10,
    requestedBy:'rick'
};

const sendMoney = ()=>{};

active && loan && sendMoney();

3、Function Delegation

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

重构代码:

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

重构代码:

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、函数对象

我们知道在 JS 中函数是尤其重要,所以使用它,我们也可以将代码拆分成一个函数对象。如下面一个改造示例

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

重构代码:

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、多态性

多态性是一个对象具有多种形式的能力。 OOP 中多态性最常见的用法是使用父类引用来引用子类对象。

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

重构代码:

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

今天的分享就到这里,这6个小技巧,是不是很棒呢,你怎么看呢?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK