在 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 開啟”選項。
輸出
這將生成以下輸出 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP