javascript 関数をbreak文で終了させる

javascript 関数をbreak文で終了させる

javascriptで、関数をbreak文で終了させるサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.134

break文で終了

関数をbreak文で終了させるには、「ラベル」を使用します。

実際に、使用して終了させてみます。

function hoge(){
  foo : {      
        console.log( 'a' )

        let flg = true
        
        if(flg) break foo

        console.log( 'b' )

        return false  
    }    
}

hoge() // a しか表示されない

実行結果

サンプルコード

以下は、
「実行」ボタンをクリックした際に、フォームの値を取得して「mebee」であるかを判定して結果を表示するだけのサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>

<script>

  window.onload = () => {

    btn.onclick = () => {

      lbl: {

        if (txt.value === 'mebee'){
          foo.innerHTML = 'mebeeです'
          break lbl
        }

        foo.innerHTML = 'mebee以外'

      }

    }

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">

      <h1 class="font-semibold text-sky-500 text-lg mr-auto">実行結果</h1>

      <p id="foo" class="font-semibold text-lg mr-auto"></p>

      <input
        class="mb-2 shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
        id="txt" type="txt">

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-sky-500 text-sky-700 font-semibold hover:text-white py-2 px-4 border border-sky-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、結果が表示されていることが確認できます。