Home >Web Front-end >JS Tutorial >How Can I Efficiently Check if a Variable Equals One of Multiple Values in JavaScript?

How Can I Efficiently Check if a Variable Equals One of Multiple Values in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-28 21:08:27137browse

How Can I Efficiently Check if a Variable Equals One of Multiple Values in JavaScript?

Simplify Variable Equality Checks Against Multiple Values

When checking a variable for equality with multiple values, a simple solution might involve an if statement with multiple conditions. However, this can become verbose.

An alternative approach is to define an object and use the in operator. However, this requires manually assigning redundant values to each item:

if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}

A Cleaner Option

In ECMA2016, JavaScript introduces the includes method on arrays. This provides a straightforward and concise solution:

if([1,3,12].includes(foo)) {
    // ...
}

This code checks if the value of foo is included in the array. If it is, the condition evaluates to true. This method is supported by all major browsers, making it a widely applicable solution.

The above is the detailed content of How Can I Efficiently Check if a Variable Equals One of Multiple Values in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn