LoginSignup
2
2

More than 5 years have passed since last update.

Array.prototype.forEachでBreakするユニークな方法

Last updated at Posted at 2015-12-31

参考:

http://stackoverflow.com/questions/2641347/how-to-short-circuit-array-foreach-like-calling-break

上のサイトの情報で、ユニークな方法がありました。

var ar = [ "apple", "lemon", "soda" ];
var breakException = {};
try {
  ar.forEach(i => {
    if (i === "lemon") {
      // breakしたい!
      throw breakException;
    }
  });
} catch (e) {
  if (e !== breakException) throw e
}

例外がスローされると、関数の実行が停止するのを応用して、

「Breakしたい!」と思ったら、強制的に例外を出しちゃうという方法です!
でも、本当の例外が発生してしまったときのために、

catch内でbreakExceptionかどうかを判断しています。

try-catch文がこんな方法に応用できるなんて面白いです!

2
2
1

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
2
2