Saturday, 24 February 2018

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

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...