0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaScriptのジャンプ文

Posted at

JSにはジャンプ文と呼ばれる文がある。ジャンプ文の種類と使い方についてメモ。

ラベル文

先頭に識別子、その後ろにコロン(:)、最後に文を記述して、任意のラベル文をつける。ラベル文を使うのはbreak文とcontinue文のみ。

mainloop:while(token !=null){
  // 複数行のコード
  continue mainloop; // 名前を付けたループ文の次のループを開始する。
  // 複数行のコード
}

break文

breakb文が実行されると、最も内側のループまたはswitch文が直ちに終了する。break文はループ文やswitch文の中で使えて、何らかの理由でループの処理を止めたい時にbreak文を使用する。

for (let i = 0; i < a.length; i++) {
  if (a[i] === target) break;
  // 複数行のコード
}

continue文

break文とよく似ている。break文は処理を終了するが、continue文は次の繰り返しからループを再開させる。

for (let i = 0; i < data.length; i++) {
  if (!data[i) continue; // 未定義の値は処理しない
  total += data[i];
}

return文

関数の呼び出しの値を指定する。関数本体の中でのみ使える。

square(2); // 4
function square(x) {
  return x * x;
}

yield文

return文と似ていて、ジェネえーター関数の中でのみ使用できる。値を生成し、生成さえた値並びにこの値を追加する。呼び出し元には戻らない。

// ある範囲の整数群を生成するジェネレータ関数
function* range(from, to) {
  for (let i = from; i <= to; i++) {
    yield i;
  }
}

勉強した本

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?