When comparing a variable to multiple predetermined values, a straightforward method is to use a series of logical OR operators:
if( foo == 1 || foo == 3 || foo == 12 ) { // ... }
Although this approach works, it can become cumbersome for a large number of values. An alternative solution is to utilize an object as follows:
if( foo in {1: 1, 3: 1, 12: 1} ) { // ... }
However, this method also introduces redundancy by requiring the repetition of values within the object.
Fortunately, in ECMA2016, a more elegant and performant solution is available: the includes method. This method allows you to efficiently check if a value is contained within an array:
if([1,3,12].includes(foo)) { // ... }
This syntax provides a concise and efficient way to perform equality checks against multiple values. Supported by all major browsers, it is the recommended approach for such comparisons.
The above is the detailed content of What's the Most Efficient Way to Check Variable Equality Against Multiple Values in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!