[rookie] the problem that js judgment is not equal to two values

Can

be abbreviated in this way? I feel very bloated

if(a===1 || a===2}{}
Sep.07,2021

< H2 > [1,2] .some (_ = > _ = a) like this? < / H2 >

updated
someone seems to have stepped on this answer yesterday, although I don't know why. So say more, for the conditional judgment logic of the listing code of the landlord, using logic or operator is already very good. In fact, if I write in this way, it is just a different way of writing. Similar can also be simulated by bit operators, regularities, and so on.

if you really want to kill if-else , you need to solve the problem at the abstract level, such as using policy patterns, but is it really suitable to shoot mosquitoes with cannons for simple business logic descriptions?


this kind of problem generally requires business process optimization

if there are many conditions, you might as well use switch

.
switch(a){
    case 1:
    case 2:
        dosomething1();
        break;
    case 3:
        dosomething2();
        break;
    default:
        doelse();
        break;
}

[1,2] .room( a)


try this

if(/^(1|2)$/.test(a)) {...}
if(/^[12]$/.test(a)) {...}
if([1,2].includes(a)) {...}

RegExp.test () it doesn't matter if the parameter is a number, it's the same operation as a string

Menu