简体   繁体   中英

Alternative way to write if statement in javascript

I am in the process of shrinking my javascript code and I was wondering if there is a more elegan way to write this huge if statement:

if (operator_list == "=" || operator_list == "<>" || operator_list == ">" || operator_list == "<" || operator_list == ">=" || operator_list == "<=" )

Any ideas?

Use an array and check if it includes operator_list

let checkArr = ["=", "<>", ">", "<", ">=", "<="];
if (checkArr.includes(operator_list)) {}

You could take a regular expression for it.

 function test(s) { return /^(=|<>|>|<|>=|<=)$/.test(s); } console.log(["=", "<>", ">", "<", ">=", "<=", 'foo', '<a='].map(test)); 

I think refactoring the expression to a function and giving it a good name would make it more elegant:

if (isValidOperator(operator_list) ) {
 // Do something
}

function isValidOperator(operator) {
  return operator == "=" || operator == "<>" || operator == ">" || operator == "<" || operator == ">=" || operator == "<=";
}

This way you explain to the readers of your code what it is meant to do. In a later stage someone can refactor the function to make it easier to understand.

Other reads:

You can make the array of acceptable operators

var arr = [ "=", "<=" ];

then check if operator is one of the elements of the array

arr.indexOf( operator_list ) != -1 //will return true if operator_list is in arr

Instead of an if-test consider an in-array test , as follows:

 var arrOps = ['=','<>','>','<','>=','<=']; var op = '='; console.log ("Valid operator? ", arrOps.indexOf(op) != -1); 

The advantage of using the array's indexOf method is that it enjoys greater browser compatbility than the includes method; see here and here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM