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

0

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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?)

Comments

0

Use indexOf

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

Test cases:

search(["a","b"], "a"); // true
search(["a","b"], "c"); //false

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.