当サイトは、アフィリエイト広告を利用しています
JavaScript(TypeScript)の
findメソッドは配列もしくはオブジェクト配列から対象の要素を検索して取得する時に使う。
type article = {title: string;tags: string[];cotent: string;};// 記事一覧const articleList: Array<article> = Array.of({ title: "記事1", tags: ["java"], cotent: "aaaaaaaaaa" },{ title: "記事2", tags: ["react"], cotent: "bbb" },{ title: "記事3", tags: ["emotion"], cotent: "cccc" },{ title: "記事4", tags: ["javascript"], cotent: "ddddddddddddd" },{ title: "記事5", tags: ["css"], cotent: "eeeeeeeeeee" },{ title: "記事6", tags: ["gatsby"], cotent: "f" });// find// 条件に一致した最初のオブジェクトが返却されるconst findResult: article | undefined = articleList.find((article) => article.title === "記事1");console.log(findResult);
findIndexメソッドも配列もしくはオブジェクト配列から対象のindexを取得したい時に使う
type article = {title: string;tags: string[];cotent: string;};// 記事一覧const articleList: Array<article> = Array.of({ title: "記事1", tags: ["java"], cotent: "aaaaaaaaaa" },{ title: "記事2", tags: ["react"], cotent: "bbb" },{ title: "記事3", tags: ["emotion"], cotent: "cccc" },{ title: "記事4", tags: ["javascript"], cotent: "ddddddddddddd" },{ title: "記事5", tags: ["css"], cotent: "eeeeeeeeeee" },{ title: "記事6", tags: ["gatsby"], cotent: "f" });// findIndex// 条件に一致した最初のオブジェクトのindexが返却されるconst findIndexResult: number = articleList.findIndex((article) => article.title === "記事4");console.log(findIndexResult);
indexOfは配列から対象の要素のindexを取得したいときに使う。
※オブジェクト配列では使用できない
// indexOf// 配列の場合はindexOfで対象のindexを取得できる// ※オブジェクト配列では使えないconst stringArray: Array<string> = ["aaa", "bbb", "ccc"];const indexOfResult: number = stringArray.indexOf("bbb");console.log(indexOfResult);
下記で動作確認してみてください!
実際に調べて整理してみると違いと用途は全然違うことがわかった。
これでjavascriptでは混乱しなくて済みそうです
実はjavaにもややこしい名前のfindFirstとfindAnyというメソッドがあったりします...
このおかげでfrontでjavascript、backendがjavaのシステム開発時などは毎回ググってました。
javaのfindFirstとfindAnyについては下記記事でまとめているのでよければ参照ください