Pages

Javascript Array indexOf() Method

4/7/14

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

No comments:

Post a Comment

Related Posts