• JavaScript Video Tutorials

JavaScript - Array indexOf() Method



Description

JavaScript array indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Syntax

Its syntax is as follows −

array.indexOf(searchElement[, fromIndex]);

Parameter Details

  • searchElement − Element to locate in the array.

  • fromIndex − The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned.

Return Value

Returns the index of the found element.

Compatibility

This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script.

if (!Array.prototype.indexOf) {
   Array.prototype.indexOf = function(elt /*, from*/) {
      var len = this.length;
      
      var from = Number(arguments[1]) || 0;
      from = (from < 0)
      ? Math.ceil(from)
      : Math.floor(from);
      
      if (from < 0)
      from += len;
      
      for (; from < len; from++) {
         if (from in this &&
         this[from] === elt)
         return from;
      }
      return -1;
   };
}

Example

Try the following example.

<html>
   <head>
      <title>JavaScript Array indexOf Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         if (!Array.prototype.indexOf) {
            Array.prototype.indexOf = function(elt /*, from*/) {
               var len = this.length;
               
               var from = Number(arguments[1]) || 0;
               from = (from < 0)
               ? Math.ceil(from)
               : Math.floor(from);
               
               if (from < 0)
               from += len;
               
               for (; from < len; from++) {
                  if (from in this &&
                  this[from] === elt)
                  return from;
               }
               return -1;
            };
         }
         var index = [12, 5, 8, 130, 44].indexOf(8);
         document.write("index is : " + index ); 
         
         var index = [12, 5, 8, 130, 44].indexOf(13);
         document.write("<br />index is : " + index ); 
      </script>      
   </body>
</html>

Output

index is : 2
index is : -1 
javascript_arrays_object.htm
Advertisements