indexOf

 

Summary

Returns the first index at which a given element can be found in the array, or -1 if it is not present.

Method of Array
Implemented in: JavaScript 1.6 (Gecko 1.8b2 and later)
ECMAScript Edition: ECMA-262 Edition 5

Syntax

var index = array.indexOf(searchElement[, fromIndex]);

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, i.e. the array will not be searched. If negative, it is taken as the offset from the end of the array. Note that even when the index is negative, the array is still searched from front to back. If the calculated index is less than 0, the whole array will be searched.

Description

indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

Compatibility

indexOf is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of indexOf in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming ObjectTypeErrorNumber, Math.floor, Math.abs, and Math.max have their original value.  

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n)
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}

Examples

Example: Using indexOf

The following example uses indexOf to locate values in an array.

var array = [2, 5, 9];
var index = array.indexOf(2);
// index is 0
index = array.indexOf(7);
// index is -1

Example: Finding all the occurrences of an element

The following example uses indexOf to find all the indices of an element in a given array, using push to add them to another array as they are found.

var indices = [];
var idx = array.indexOf(element);
while (idx != -1)
{
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}

See also

lastIndexOf

Tags (0)

Attachments (0)

 

Attach file