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

Array.prototype.findIndex() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Array.prototype.findIndex()

Baseline

20159

findIndex() Array -1

find()

const array = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array.findIndex(isLargeNumber));
// : 3

js
findIndex(callbackFn)
findIndex(callbackFn, thisArg)

callbackFn

element

index

array

findIndex()

thisArg

callbackFn this

-1

findIndex() callbackFn callbackFn findIndex() callbackFn findIndex() -1

callbackFn undefined

findIndex() this length

-1

js
function isPrime(n) {
  if (n < 2) {
    return false;
  }
  if (n % 2 === 0) {
    return n === 2;
  }
  for (let factor = 3; factor * factor <= n; factor += 2) {
    if (n % factor === 0) {
      return false;
    }
  }
  return true;
}

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

: isPrime()

callbackFn 3

array filter() findIndex()

js
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const firstTrough = numbers
  .filter((num) => num > 0)
  .findIndex((num, idx, arr) => {
    // arr 
    // 
    if (idx > 0 && num >= arr[idx - 1]) return false;
    if (idx < arr.length - 1 && num >= arr[idx + 1]) return false;
    return true;
  });
console.log(firstTrough); // 1

findIndex()

undefined

js
console.log([1, , 3].findIndex((x) => x === undefined)); // 1

findIndex()

findIndex() this length length

js
const arrayLike = {
  length: 3,
  "-1": 0.1, // -1 < 0  findIndex() 
  0: 2,
  1: 7.3,
  2: 4,
};
console.log(
  Array.prototype.findIndex.call(arrayLike, (x) => !Number.isInteger(x)),
); // 1

ECMAScript 2027 LanguageSpecification
# sec-array.prototype.findindex


Web Proxy Viewer  |  New URL  |  Original Page