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

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

Baseline Widely available

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

findIndex() , . -1.

find(), .

In this article

arr.findIndex(callback[, thisArg])

callback

, , :

element

.

index

.

array

, .

thisArg

. , this callback.

findIndex callback , , , true. , findIndex . , findIndex -1. callback , ; , .

callback : , , .

findIndex thisArg, callback this. this undefined.

findIndex , .

, findIndex, callback. , findIndex, callback. , callback, , , , findIndex ; .

:

, ( -1, ).

js
function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

console.log([4, 6, 8, 12].findIndex(isPrime)); // -1,  
console.log([4, 6, 7, 12].findIndex(isPrime)); // 2

ECMAScript 6 JavaScript. , :

js
if (!Array.prototype.findIndex) {
  Array.prototype.findIndex = function (predicate) {
    if (this == null) {
      throw new TypeError(
        "Array.prototype.findIndex called on null or undefined",
      );
    }
    if (typeof predicate !== "function") {
      throw new TypeError("predicate must be a function");
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return i;
      }
    }
    return -1;
  };
}

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


Web Proxy Viewer  |  New URL  |  Original Page