避免在我们的 JS 脚本中使用 IF
我写这篇文章是因为最近我一直在处理 JS 源代码,其中的 if 语句数量之多,
是我从未见过的。因此,我认为分享这些简单的技巧非常重要,它们可以帮助我们在编写代码时无需考虑“if”语句。
我将解释 6 种实现此目的的方法。这样做的目的并非为了让您陷入永远不使用 IF 的偏执,而是为了开拓思路,让我们以全新的方式思考 JS 中的决策。
类别:
1)三元运算符:
我们正在谈论这个“条件?表达式1:表达式2 ”,非常简单。
例 1:
- 带有 IF 的代码:
function saveCustomer(customer) {
if (isCustomerValid(customer)) {
database.save(customer)
} else {
alert('customer is invalid')
}
}
- 重构代码:
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:
- 带有 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
}
}
- 重构代码:
// ES6 style custom formatted ternary magic
const customerValidation = customer =>
!customer.email ? error('email is required')
: !customer.login ? error('login is required')
: !customer.name ? error('name is required')
: customer
示例 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;
}
- 重构代码:
function getEventTarget(evt) {
evt = evt || window.event;
return evt && (evt.target || evt.srcElement);
}
2)短路:
它是一种使用 AND 和 OR 运算符来评估表达式的技术。
https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb
true || true;
// true
true || false;
// true
false || false;
// false
例 1:
- 带有 IF 的代码:
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
};
//Apply the short circuit to avoid the if.
isOnline&&makeReservation(user);
示例 2:
- 带有 IF 的代码:
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 = ()=>{};
//Apply short circuit in this case, the loan is evaluated true because !=undefined
active && loan && sendMoney();
3)功能委托:
该技术将短路和分离代码块与功能混合在一起。
例 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;
}
}
- 重构代码:
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 语句。其思路是创建一个包含键/值的映射,并使用函数
访问作为参数传递的键的值。
这个想法来自这个链接:https://medium.com/chrisburgin/rewriting-javascript-replacing-the-switch-statement-cfff707cf045
例 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'
}
- 重构代码:
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 中函数是第一类,因此使用它可以将代码拆分为函数对象。
例 1:
- 带有 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
- 重构代码:
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
5)多态性:
多态性是指对象具有多种形态的能力。在面向对象编程 (OOP) 中,多态性最常见的用法是使用父类引用来指向子类对象。
例 1:
- 带有 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));
- 重构代码:
//Create function to different behaviour, same parameter call.
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
};
//Same call.
console.log('Salary',bob.calc(bob.salary));
console.log('Salary',mary.calc(mary.salary));
阅读材料:
有关同一主题的有趣链接列表。
- https://www.google.com/amp/s/javascriptweblog.wordpress.com/2010/07/26/no-more-ifs-alternatives-to-statement-branching-in-javascript/amp/
- http://adripofjavascript.com/blog/drips/using-duck-typing-to-avoid-conditionals-in-javascript.html
- https://hackernoon.com/rethinking-javascript-the-if-statement-b158a61cd6cb
- https://stackoverflow.com/questions/57023787/descending-order-with-if-else-and-not-use-logical-operators-javascript
- https://medium.com/front-end-weekly/javascript-path-to-eliminating-if-else-dab7a1912024
- https://medium.com/edge-coders/coding-tip-try-to-code-without-if-statements-d06799eed231
访问我的 github 了解更多项目!!
https://github.com/damiancipolat? tab=repositories