在 JavaScript 中將函式分配給變數?


使用 return 語句將函式分配給變數。以下為程式碼 −

示例

 即時演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
   .demo {
      background: skyblue;
      height: 20px;
      width: 75%;
      margin: 10px;
      padding: 10px;
   }
</style>
</head>
<body>
<div class="demo" data-st="John">John Smith</div>
<div class="demo" data-st="David">David Miller</div>
<div class="demo" data-st="Adam">Adam Smith</div>
<script>
   var studentNames = function() {
      var names = [];
      $(".demo").each(function() {
         names.push($(this).data('st'));
      });
      return names.join();
   };
   console.log( studentNames() );
</script>
</body>
</html>

要執行以上程式,請儲存檔名“anyName.html(index.html)”,然後右鍵單擊該檔案。在 VS Code 編輯器中選擇“使用 Live Server 開啟”選項。

輸出

這將生成以下輸出 −

更新日期: 2020-09-11

145 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.