FindメソッドとFindIndexメソッド
CoddyのJavaScriptジャーニー「論理とフロー」セクションの一部 — レッスン 58/65。
find() メソッドは、提供されたテスト関数を満たす配列内の最初の要素を返します。要素が見つからない場合は、undefined を返します。
findIndex() メソッドは似ていますが、要素そのものではなく、最初に一致した要素のインデックスを返します。要素が見つからない場合は、-1 を返します。
基本構文:
array.find(callback(element[, index[, array]]))
array.findIndex(callback(element[, index[, array]]))find() を使った簡単な例:
const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(num => num > 10);
console.log(found);
// 12 (10より大きい最初の数値)findIndex() を使用した同じ例:
const numbers = [5, 12, 8, 130, 44];
const foundIndex = numbers.findIndex(num => num > 10);
console.log(foundIndex);
// 1 (10より大きい最初の数値のインデックス)配列内のオブジェクトを検索する:
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'oranges', quantity: 5}
];
// find を使用する
const result = inventory.find(item => item.name === 'bananas');
console.log(result); // {name: 'bananas', quantity: 0}
// findIndex を使用する
const index = inventory.findIndex(item => item.name === 'bananas');
console.log(index); // 1このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
チートシート
find() メソッドは、テスト関数を満たす最初の要素を返します。見つからない場合は undefined を返します。
const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(num => num > 10);
console.log(found); // 12findIndex() メソッドは、一致する最初の要素のインデックスを返します。見つからない場合は -1 を返します。
const numbers = [5, 12, 8, 130, 44];
const foundIndex = numbers.findIndex(num => num > 10);
console.log(foundIndex); // 1配列内のオブジェクトを検索する:
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'oranges', quantity: 5}
];
const result = inventory.find(item => item.name === 'bananas');
// {name: 'bananas', quantity: 0}
const index = inventory.findIndex(item => item.name === 'bananas');
// 1自分で試してみよう
このレッスンにはコードチャレンジは含まれていません。
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。