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

Array.prototype.lastIndexOf() - 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.lastIndexOf()

Baseline
Widely available

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

lastIndexOf() , -1, . , fromIndex.

In this article

const animals = ["Dodo", "Tiger", "Penguin", "Dodo"];

console.log(animals.lastIndexOf("Dodo"));
// Expected output: 3

console.log(animals.lastIndexOf("Tiger"));
// Expected output: 1

arr.lastIndexOf(searchElement[, fromIndex = arr.length])

searchElement

.

fromIndex

. , . , . , . : , . 0, . , , .

lastIndexOf() searchElement , ( ===, ).

: lastIndexOf()

lastIndexOf() .

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

:

lastIndexOf() , push() .

js
var indices = [];
var array = ["a", "b", "a", "c", "a", "d"];
var element = "a";
var idx = array.lastIndexOf(element);
while (idx != -1) {
  indices.push(idx);
  idx = idx > 0 ? array.lastIndexOf(element, idx - 1) : -1;
}

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

, idx == 0 , , fromIndex, . indexOf().

lastIndexOf() ECMA-262 5- ; . , , lastIndexOf() , . , ECMA-262 5- ; , Object, TypeError, Number, Math.floor(), Math.abs() Math.min() .

js
//   ECMA-262, 5- , 15.4.4.15
//  (en): http://es5.github.io/#x15.4.4.15
//  (ru): http://es5.javascript.ru/x15.4.html#x15.4.4.15
if (!Array.prototype.lastIndexOf) {
  Array.prototype.lastIndexOf = function (searchElement /*, fromIndex*/) {
    "use strict";

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

    var n,
      k,
      t = Object(this),
      len = t.length >>> 0;
    if (len === 0) {
      return -1;
    }

    n = len - 1;
    if (arguments.length > 1) {
      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));
      }
    }

    for (k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k >= 0; k--) {
      if (k in t && t[k] === searchElement) {
        return k;
      }
    }
    return -1;
  };
}

, lastIndexOf(), Firefox JavaScript SpiderMonkey, , . , from , .

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


Web Proxy Viewer  |  New URL  |  Original Page