Wednesday, 30 August 2017

comparison - JavaScript: Simple way to check if variable is equal to two or more values?




Is there an easier way to determine if a variable is equal to a range of values, such as:




if x === 5 || 6 


rather than something obtuse like:



if x === 5 || x === 6


?


Answer




You can stash your values inside an array and check whether the variable exists in the array by using [].indexOf:



if([5, 6].indexOf(x) > -1) {
// ...
}


If -1 is returned then the variable doesn't exist in the array.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...