Thursday 23 June 2016

javascript - how to simplify this statement using indexOf?





How can I simplfy the following text inside the if statement in Javascript using "indexof"?



if (a === 1 || a === 2 || a === 3) {
return "correct";
};



I am guessing an array needs to be made for 1,2, and 3, but am unsure of how to us instanceof after that



*edited to say indexOf instead of instanceOf


Answer




The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.





In your case, instanceof wont help you. You can use indexOf() with array as follow.



var arr = [1, 2, 3];

// Check if a is present in the arr array
if (arr.indexOf(a) > -1) {
return "correct";
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...