Copyright © tutorialspoint.com

Javascript Array indexOf() Method

previous next

Advertisements


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:

array.indexOf(searchElement[, fromIndex]);

Here is the detail of parameters:

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 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:

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

This will produce following result:

index is : 2
index is : -1 

To understand it in better way you can Try it yourself.


previous next

Copyright © tutorialspoint.com