-2

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

chanchal karn
  • 517
  • 2
  • 7
  • 11

4 Answers4

1

You can use the indexOf() function you simply do this : array.indexOf("string") It will return -1 if the item is not found, otherwise just the position. Here's a link W3Schools.

McLinux
  • 263
  • 1
  • 10
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

Use indexOf

function search(arr,obj) {
    return (arr.indexOf(obj) != -1);
}

Test cases:

search(["a","b"], "a"); // true
search(["a","b"], "c"); //false
SK.
  • 4,174
  • 4
  • 30
  • 48
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