I am learning JavaScript and i came across this problem. I want to catch an input value using document.formName.elementName.value
and compare that value with an instance of an Array object.If the value exists it will throw an alert!.
Asked
Active
Viewed 399 times
-2

chanchal karn
- 517
- 2
- 7
- 11
4 Answers
0
I think that has been asked thousands of times:
if(myFancyArray.indexOf(document.formName.elementName.value) !== -1){
alert("You did something wrong!");
}
Watch out as old versions of IE don’t know indexOf
. (but who needs IE?)

idmean
- 14,540
- 9
- 54
- 83
0
You can add a convenience method to JavaScript's Array
Array.prototype.includes = function(element) {
var found = false;
for (var i = 0; i < this.length; i++) {
if (this[i] == element) {
found = true;
}
}
return found;
}
And, then, you can use below code to get some syntactic sugar
var myArray = [0,1,"hello","world"];
console.log(myArray.includes("hello")); //prints true
console.log(myArray.includes(10)); //prints false

Wand Maker
- 18,476
- 8
- 53
- 87