在 JavaScript 中將所有宣告放在頂部是一種好習慣嗎?


是的,這是一種好的做法,可以將所有的 JavaScript 宣告都放在最前面。我們來看一個示例 -

示例

<html>
   <head>
      <title>JavaScript String match() Method</title>
   </head>

   <body>
      <script>
         // all the variables declared at top
         var str, re, found;
         
         str = "For more information, see Chapter 3.4.5.1";
         re = /(chapter \d+(\.\d)*)/i;
         found = str.match( re );
         document.write(found );
      </script>
   </body>
</html>

以下是它的優點 -

  • 為檢查所有變數提供了一個單一的位置。
  • 幫助避免全域性變數
  • 避免重新宣告。
  • 對於其他人來說,程式碼也很容易閱讀。

更新時間: 2020 年 5 月 20 日

88 次瀏覽

啟動你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.