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!.
4 Answers
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.
Comments
Use indexOf
function search(arr,obj) {
return (arr.indexOf(obj) != -1);
}
Test cases:
search(["a","b"], "a"); // true
search(["a","b"], "c"); //false
Comments
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