LoginSignup
1

More than 3 years have passed since last update.

プレーンのJavaScriptで配列を回したいときはfindが便利

Posted at

こんな配列があります。

const fruit = ["apple", "banana", "mango"];

for分の場合

一致したものを取得したいときに以下のように書いていました。

const fruit = ["apple", "banana", "mango"];
const target = "mango"; 
for (var i = 0; i < fruit.length i++) {
  if (target === fruit[i] {
    console.log("mangoと一致!");
  }
}

findを使った場合

const fruit = [apple, banana, mango];
const target = mango; 
const found = fruit.find(element => element === target); // mango

まとめ

簡単にかつシンプルにコードを書けるようになるので便利です。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1