JavaScript xxx .findIndex is not a functionの解決方法

環境
Google Chrome  114.0.5735.199(Official Build) (64 ビット)
Windows 11 Pro 64bit

修正前コード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const obj = {
"ta": 21,
"tb": 32,
"tc": 43
};
const result = obj.findIndex(v => v % 2 === 0);
const obj = { "ta": 21, "tb": 32, "tc": 43 }; const result = obj.findIndex(v => v % 2 === 0);
const obj = {
    "ta": 21,
    "tb": 32,
    "tc": 43
};

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

エラーメッセージ
Error: obj.findIndex is not a function

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

修正後コード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const obj = {
"ta": 21,
"tb": 32,
"tc": 43
};
console.log( Object.values(obj) );
const result = Object.values(obj).findIndex(v => v % 2 === 0);
console.log( result );
const obj = { "ta": 21, "tb": 32, "tc": 43 }; console.log( Object.values(obj) ); const result = Object.values(obj).findIndex(v => v % 2 === 0); console.log( result );
const obj = {
    "ta": 21,
    "tb": 32,
    "tc": 43
};

console.log( Object.values(obj) ); 

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

console.log( result );

実行結果
> Array [21, 32, 43]
> 1

JavaScript

Posted by arkgame