Is There A Better Way To Write || In A Single If Statment
was wondering if there is a better way to write the code below. I want my if statement to ignore all of the keycodes. but seems quite a messy way to write it as below. thanks! if (
Solution 1:
Using includes
:
if ([9, 91, 20, 18, 17, 37].includes(event.keyCode))
Solution 2:
For a larger list of values that you compare with often, it may be more optimal to use a Set
.
const codes = new Set([9, 91, 20, 18, 17, 37]);
if(codes.has(event.keyCode)){
// do something
}
Solution 3:
You can use Array#some
or Array#indexOf
instead.
if ([9, 91, 20, 18, 17, 37].some(val => val === event.keyCode))
or
if ([9, 91, 20, 18, 17, 37].indexOf(event.keyCode) !== -1)
In terms of performance, I would highly recommend you should use indexOf
.
And another aspect you should take care of is between includes
and indexOf
in case of NAN
issue. There are 2 posts below that can help you have comprehensive knowledge about them:
Solution 4:
Like others have said, you can create an array or set with the valid key codes and test for membership using the event.keyCode variable. I wrote some example code below for how you could do this in a clean way :)
// let eventKeyCode = event.keyCode;let eventKeyCode = 28;
let validKeyCodes = [9, 91, 20, 18, 17, 37];
if (validKeyCodes.includes(eventKeyCode)) {
// do something console.log(`event has valid key code: ${eventKeyCode}`);
} else {
// catch logicconsole.log(`event has invalid key code: ${eventKeyCode}`);
}
Solution 5:
You can pass the if logic into a function.
functionisValidKey(keyCode) {
const validKeys = [9, 91, 20, 18, 17, 37];
return validKeys.includes(keyCode);
}
//...if (isValidKey(event.keyCode)) ...
Post a Comment for "Is There A Better Way To Write || In A Single If Statment"