I was wondering if there is a way to check multiple conditions for the same variable or value without repeating that value.
For example, if I had the variable keyCode
, and I wanted to check if it was greater than 102, or less than 48, or between 65 and 57, or between 70 and 97, I would have to write this:
var keyCode = // some value;
if(
keyCode > 102 ||
keyCode < 48 ||
(keyCode > 57 && keyCode < 65) ||
(keycode > 70 && keyCode < 97)
) {
// do something
}
As you can see, I write keyCode
in the if
condition 6 times. If the condition were more complex (this one simply rules out all non-hexadecimal characters), then it could be even more repetitive.
I was wondering if there was a way to simplify this. Maybe something like this:
if(
keyCode > 102 || < 48 || (> 57 && < 65) || (> 70 && < 97)
) {
// do something
}
in which you could simply omit the variable name and just put many conditionals on a single variable. It's like the opposite of this question, in which the asker was wondering if there was a way to check multiple variables against a single condition.
I'm coding in JS now, but if you know implementations of this in any other language, that might be helpful in the future as well. I thought there would be an easy implementation of this, because I use it so often, but I was surprised to see that I couldn't find any information on any language feature like this at all.
Aucun commentaire:
Enregistrer un commentaire