简体   繁体   中英

javascript: best way to check if element exists in pre populated collection?

We are creating a function that would return true if input passed is in certain pre-defined values:

function isEligbile(input){
    return (input == 1 || input == 24 || input == 17);
}

OR

function isEligbile(input){
   var eligibleInputs = {1: true, 24: true, 17: true};
   return eligibleInputs[input]; 
}

I have just mentioned 3 eligible inputs but list is too long. Which is best approach to do such comparison?

You don't need an object literal to store your values, just an array from which you can check for authorized values with indexOf() :

function isEligible(input){
   var eligibleInputs = [1, 24, 17];
   return eligibleInputs.indexOf(input) != -1;
}

Please note that in your case the object literal is not a bad choice. It may be longer to write but also faster in execution.

If you are sure about wanting to hardcode the eligible inputs, I would suggest:

function isEligible(input) {
    var eligibleInputs = [1, 17, 24];
    return eligibleInputs.includes(input);
}

However, if the list of eligible inputs is really long or subject to change, you might want to consider using a different solution, like loading the list from an external source.

The reason I find the snippet above to be a better solution than OPs code is because

  • It is easier to expand this list (less characters to type)
  • It is a lot more elegant than having an if-statement with an option for every single element
  • You can easily iterate over the array if needed for other things

Note: The function in your code is called 'isEligbile' instead of 'isEligible', you might want to fix this.

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