javascript エラー「Uncaught TypeError: xxx.findIndex is not a function」の解決方法

javascript エラー「Uncaught TypeError: xxx.findIndex is not a function」の解決方法

javascriptで、エラー「Uncaught TypeError: xxx.findIndex is not a function」が発生した場合の原因と解決方法を記述してます。配列でない値に対して「findIndex」を使用した場合に発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 108.0.5359.125

エラー内容

以下の、オブジェクトに対して「findIndex」を使用した際に発生。

const obj = {
    "a": 1,
    "b": 2,
    "c": 3
};

const result = obj.findIndex(v => v % 2 === 0);

エラーメッセージ

Uncaught TypeError: obj.findIndex is not a function

画像

firefox106の場合でも同じエラーが発生します。

Uncaught TypeError: obj.findIndex is not a function

画像

safari15.5では、以下のエラーとなります。

TypeError: obj.findIndex is not a function. (In 'obj.findIndex(v => v % 2 === 0)', 'obj.findIndex' is undefined)

画像

原因

配列でないものに「findIndex」を使用しているため
※「findIndex」は配列内で条件に見つかった最初の値を取得します。

const arr = [1, 2, 3];

const result = arr.findIndex(v => v % 2 === 0);

console.log( result );
// 1

解決方法

オブジェクトの「value」に対して条件を指定するなら「Object.values」を使用して「value」のみを配列化して「findIndex」を使用する

const obj = {
    "a": 1,
    "b": 2,
    "c": 3
};;

console.log( Object.values(obj) ); // [1, 2, 3]

const result = Object.values(obj).findIndex(v => v % 2 === 0);

console.log( result );
// 1

もしくは、配列であるかを判定してから使用します。

const obj = {
    "a": 1,
    "b": 2,
    "c": 3
};

const result = Array.isArray(obj) ? obj.findIndex(element => element % 2 === 0) : '配列ではありません';

console.log( result );
// 配列ではありません