Wednesday 7 November 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...