LoginSignup
107
64

More than 1 year has passed since last update.

forループとforEach内でreturnした時の挙動の違い

Last updated at Posted at 2015-06-24

#forループ内とforEach内では挙動が違う
あるeventの中に、自分が参加者に入っているか確認するプログラム。
参加者に自分がいればtrue、いなければfalseを返したい。

for文と同じ感覚てforEachを使ってしまい、returnが期待した値にならずはまった。

#実際のコードでの比較

##for文の場合

for文
for (i = 0; i < participants.length; i++) {
        if(participants[i].id == myID) {
          return true;
        }
    }
return false;

participants[i].id == myIDがtrueになったとき、for文もメソッドも抜けてtrueがreturnされる。

##forEach文の場合

forEach
participants.forEach(function (participant) {
        if(participant.id == myID) {
          return true;
        }
})
return false;

forEachの場合、participantsの全ての要素に対して処理を実行する。
処理の中でreturnしても、forEach文を抜けることは出来ない。

participant.id == myIDがtrueになっても、次の要素に対する処理に移る。
そして最終的にforEachを抜けて、必ず undefined がreturnされる

107
64
5

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
107
64