mozilla

Revision 371209 of Array.prototype.indexOf()

  • Revision slug: JavaScript/Reference/Global_Objects/Array/indexOf
  • Revision title: Array indexOf method
  • Revision id: 371209
  • Created:
  • Creator: tw2113
  • Is current revision? No
  • Comment

Revision Content

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
ECMAScript Edition ECMAScript 5th Edition

Syntax

array.indexOf(searchElement[, fromIndex])

Parameters

searchElement
Element to locate in the array.
fromIndex

Default: 0 (Entire array is searched)

The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then 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 utilizing the following code at the beginning of your scripts. This will allow you to use indexOf when there is still no native support. This algorithm matches the one specified in ECMA-262, 5th edition, assuming Object, TypeError, Number, Math.floor, Math.abs, and Math.max have their original values.

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (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 > 1) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                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 assigned 0
index = array.indexOf(7); // index is assigned -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);
}

Browser compatibility

Based on Kangax's compat tables

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} 9 {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}

See also

Revision Source

<h2 id="Summary" name="Summary">Summary</h2>
<p>Returns the first index at which a given element can be found in the array, or -1 if it is not present.</p>
<table class="standard-table">
  <thead>
    <tr>
      <th class="header" colspan="2">Method of <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="JavaScript/Reference/Global_Objects/Array"><code>Array</code></a></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Implemented in</td>
      <td>JavaScript 1.6</td>
    </tr>
    <tr>
      <td>ECMAScript Edition</td>
      <td>ECMAScript 5th Edition</td>
    </tr>
  </tbody>
</table>
<h2 id="Syntax" name="Syntax">Syntax</h2>
<pre class="syntaxbox">
<code><em>array</em>.indexOf(<em>searchElement</em>[, <em>fromIndex</em>])</code></pre>
<h3 id="Parameters" name="Parameters">Parameters</h3>
<dl>
  <dt>
    <code>searchElement</code></dt>
  <dd>
    Element to locate in the array.</dd>
  <dt>
    <code>fromIndex</code></dt>
  <dd>
    <p>Default: 0 (Entire array is searched)</p>
    The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched.</dd>
</dl>
<h2 id="Description" name="Description">Description</h2>
<p><code>indexOf</code> compares <code>searchElement</code> to elements of the Array using <a href="/en-US/docs/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators" title="JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators">strict equality</a> (the same method used by the ===, or triple-equals, operator).</p>
<h2 id="Compatibility" name="Compatibility">Compatibility</h2>
<p><code>indexOf</code> 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 utilizing the following code at the beginning of your scripts. This will allow you to use <code>indexOf</code> when there is still no native support. This algorithm matches the one specified in ECMA-262, 5th edition, assuming <code style="color: inherit; font-weight: inherit; ">Object</code>, <code>TypeError</code>, <code>Number</code>, <code>Math.floor</code>, <code>Math.abs</code>, and <code>Math.max</code> have their original values.</p>
<!-- var DO_NOT_MODIFY_THE_FOLLOWING_CODE_IN_ANY_WAY = 0; -->
<pre class="brush: js">
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length &gt;&gt;&gt; 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length &gt; 1) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 &amp;&amp; n != Infinity &amp;&amp; n != -Infinity) {
                n = (n &gt; 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n &gt;= len) {
            return -1;
        }
        var k = n &gt;= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k &lt; len; k++) {
            if (k in t &amp;&amp; t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}
</pre>
<h2 id="Examples" name="Examples">Examples</h2>
<h3 id="Example:_Using_indexOf" name="Example:_Using_indexOf">Example: Using indexOf</h3>
<p>The following example uses <code>indexOf</code> to locate values in an array.</p>
<pre class="brush: js">
var array = [2, 5, 9];
var index = array.indexOf(2); // index is assigned 0
index = array.indexOf(7); // index is assigned -1
</pre>
<h3 id="Example:_Finding_all_the_occurrences_of_an_element" name="Example:_Finding_all_the_occurrences_of_an_element">Example: Finding all the occurrences of an element</h3>
<p>The following example uses <code>indexOf</code> to find all the indices of an element in a given array, using <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/push" title="JavaScript/Reference/Global_Objects/Array/push">push</a> to add them to another array as they are found.</p>
<pre class="brush: js">
var indices = [];
var idx = array.indexOf(element);
while (idx != -1) {
    indices.push(idx);
    idx = array.indexOf(element, idx + 1);
}</pre>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>Based on <a class="external" href="http://kangax.github.com/es5-compat-table/">Kangax's compat tables</a></p>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Chrome</th>
        <th>Firefox (Gecko)</th>
        <th>Internet Explorer</th>
        <th>Opera</th>
        <th>Safari</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{ CompatVersionUnknown() }}</td>
        <td>{{ CompatVersionUnknown() }}</td>
        <td>9</td>
        <td>{{ CompatVersionUnknown() }}</td>
        <td>{{ CompatVersionUnknown() }}</td>
      </tr>
    </tbody>
  </table>
</div>
<div id="compat-mobile">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Android</th>
        <th>Chrome for Android</th>
        <th>Firefox Mobile (Gecko)</th>
        <th>IE Mobile</th>
        <th>Opera Mobile</th>
        <th>Safari Mobile</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
      </tr>
    </tbody>
  </table>
</div>
<h2 id="See_also" name="See_also">See also</h2>
<ul>
  <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/lastIndexOf" title="JavaScript/Reference/Global_Objects/Array/lastIndexOf">Array.lastIndexOf</a></li>
</ul>
Revert to this revision