[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf [Back]  [Original]

Array.prototype.indexOf() - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

Array.prototype.indexOf()

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2015 ..

indexOf() , -1, .

In this article

arr.indexOf(searchElement[, fromIndex = 0])

searchElement

.

fromIndex

, . , -1, , . , . : , . 0, . 0, , .

indexOf() searchElement , ( ===, ).

: indexOf()

indexOf() .

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

:

indexOf() , push() .

js
var indices = [];
var array = ["a", "b", "a", "c", "a", "d"];
var element = "a";
var idx = array.indexOf(element);
while (idx != -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}

console.log(indices);
// [0, 2, 4]

indexOf() ECMA-262 5- ; . , , indexOf() , . , ECMA-262 5- ; , TypeError Math.abs() .

js
//   ECMA-262, 5- , 15.4.4.14
//  (en): http://es5.github.io/#x15.4.4.14
//  (ru): http://es5.javascript.ru/x15.4.html#x15.4.4.14
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (searchElement, fromIndex) {
    var k;

    // 1.  O    ToObject   
    //     this   .
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }

    var O = Object(this);

    // 2.  lenValue      Get
    //     O   "length".
    // 3.  len  ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4.  len  0,  -1.
    if (len === 0) {
      return -1;
    }

    // 5.     fromIndex,  n 
    //    ToInteger(fromIndex);   n  0.
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }

    // 6.  n >= len,  -1.
    if (n >= len) {
      return -1;
    }

    // 7.  n >= 0,  k  n.
    // 8. , n<0,  k  len - abs(n).
    //     k   0,  k  0.
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    // 9.  k < len,  
    while (k < len) {
      // a.  Pk  ToString(k).
      //           in
      // b.  kPresent     
      //    HasProperty  O   Pk.
      //          c
      // c.  kPresent  true, 
      //    i.   elementK      Get
      //         O   ToString(k).
      //   ii.   same   
      //             
      //        searchElement  elementK.
      //  iii.   same  true,  k.
      if (k in O && O[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}

Specification
ECMAScript 2027 LanguageSpecification
# sec-array.prototype.indexof


Web Proxy Viewer  |  New URL  |  Original Page