Using the 'Includes' Method
When comparing a variable to a list of values, you might encounter the need for a concise and efficient approach. Traditionally, programmers would resort to multiple equality checks, but that can become tedious. This article introduces a cleaner solution using the 'includes' method.
In ECMA2016 (supported by all major browsers), the 'includes' method provides a convenient way to determine if a value exists within an array. This allows you to replace multiple equality checks with a single line:
if ([1, 3, 12].includes(foo)) { // ... }
In this instance, the 'foo' variable is being checked against an array containing [1, 3, 12]. If 'foo' is equal to any of these values, the 'if' statement will execute.
This approach is not only concise but also clear and readable. It eliminates the redundancy introduced by setting multiple values to '1' in an object and provides a direct means of testing for equality against multiple values.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3