In the given JavaScript array example, we are going to show how an array contains method().
JavaScript Array Contains Method
In the given JavaScript array example, we are going to show how an array contains method(). As you already know we required the property 'prototype' of Array class whenever we want to add or modify the methods and properties of an array. That means if we are using method contain(), we have to use prototype property in our example. Now let's see how we have used it..
JavaScript code to use contain method in an array
<html> <head> <h2>Use of contains() method</h2> <script> Array.prototype.contains = function (element) { for (var i = 0; i < this.length; i++) { if (this[i] == element) { return true; } } return false; } arr1 = ["Rose", "India", "Technologies"]; document.write("The condition is "+arr1.contains("India")+"<br>"); </script> </head> <b>[If the specified element is present in the array, it returns true otherwise returns false.]</b> </html> |
In the given code the contain method determines whether the specified element is present in the array or not. If the specified element is present in the array, it returns true otherwise it returns false.
Output of the code will be displayed as: