<style>
.slides img{background-color:grey!important}
.slides img[title^='"']{filter:invert(100%)}
hr, .slides [title^='*']{display:none}
summary h1{display:inline;border-bottom:0!important}
</style>
<!-- .slide: data-background="black" -->
###### [JavaScript 教學/](/@NCHUIT/js)
:::spoiler {state=open}<h1>函式</h1>
+ <i class="fa fa-book"></i> 網頁 md.nchuit.cc/js
+ <i class="fa fa-tv"></i> 簡報 md.nchuit.cc/js4
- [MDN](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Functions)
- [w3schools](https://www.w3schools.com/js/js_functions.asp)
[ToC]
:::
> [name=VJ]
----
## 定義
<!-- A JavaScript function is a block of code designed to perform a particular task. -->
函式(Functions)是寫來用於執行**特定任務**的程式碼區塊。
<!-- A JavaScript function is executed when "something" invokes it (calls it). -->
函式在被「某行程式碼」調用(呼叫)時執行。
```javascript=
function multiply(a, b) {
return a * b;
}
multiply(3,9)
```
----
## Why Functions?
<!-- You can reuse code: Define the code once, and use it many times. -->
1. 重複使用程式碼: 定義一次,跑千萬次
<!-- You can use the same code many times with different arguments, to produce different results. -->
2. 回傳不同結果: 傳入不同參數,產生不同回傳值
3. 寫給人家 (例: LINE Notify, gapi)
```javascript=
function BMI(身高cm,體重kg){
return 體重kg/(身高cm*.01)**2
}
alert(BMI(165,45))
alert(BMI(159,44))
```
----
## 語法
<!-- A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). -->
用`function`**關鍵字**定義,後面用括號包住**參數**
一般寫法
```javascript=
function 函式名稱(參數1, 參數2, 參數3) {
// 程式碼
}
```
物件定義寫法
```javascript=
函式名稱 = function(參數1, 參數2, 參數3) {
// 程式碼
}
```
----
## [參數 Parameters](https://developer.mozilla.org/zh-TW/docs/Glossary/Parameter)
寫函式的時候我們稱括號`()`裡的變數為**參數**
----
::: spoiler 練習: 除錯
```javascript=
function f(名, 姓){
alert(姓+名)
}
f('維傑','談')
```
:::
執行下面程式碼會怪怪的,請修改第4行讓它正常運行。
```javascript=
function f(名, 姓){
alert(姓+名)
}
f('維傑') // 改這行
```
----
::: spoiler 練習: 檢驗質數
```javascript=
function 檢驗質數(n){
if(n==2) return true
const s = n**0.5+1
for(i = 2; i < s; i++)
if(n%i==0) return false
return true
}
alert(檢驗質數(1117))
```
:::
寫一個含一個引數的函式(如下),判斷`n`是不是質數(回傳`true`或`false`)。
```javascript=
function 檢驗質數(n){
// TO-DO
}
alert(檢驗質數(1117))
```
----
## [引數 Arguments](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Functions/arguments)
呼叫函式時,我們稱傳入的資料為**引數**,下面例子將`'hello'`,`'world'`,`'!'` 三個字串傳到函式`f`中
```javascript=
function f(參數1, 參數2, 參數3) {
alert(參數1)
alert(arguments[0])
}
f('hello','world','!')
```
----
## [預設參數](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Functions/Default_parameters)
```javascript=
function f(參數1, 參數2, 參數3='!') {
alert(參數3)
}
f('hello','world')
```
----
## [其餘參數](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Functions/rest_parameters)
```javascript=
function f(a, b, ...剩下的參數) {
alert(剩下的參數[0])
alert(arguments[2])
}
f('hello','world','!')
```
----
## [解構賦值](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
```javascript=
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
// expected output: Array [30,40,50]
```
----
:::spoiler 練習: 交換兩數
```javascript=
var a=1,b=2;
[a,b]=[b,a]
alert(`a=${a},b=${b}`)
```
:::
```javascript=
var a=1,b=2;
// TO-DO
alert(`a=${a},b=${b}`)
```
----
## [回傳值 return](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/return)
要讓一個函式回傳一個值(或資料),請使用`return`。
```javascript=
function BMI(身高cm,體重kg){
return 體重kg/(身高cm*.01)**2
alert('hello')
}
x=BMI(165,45)
alert(x)
```
----
## [箭頭函式](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Functions/Arrow_functions)
就...短一點
```javascript=
f = (p1,p2) => {
if(p1>p2) return p1
else return p2
}
f(8,9)
```
```javascript=
f = (p1,p2) => p1>p2?p1:p2
f(8,9)
```
----
## [HTML 事件處理器屬性](https://developer.mozilla.org/zh-TW/docs/Web/HTML/Global_attributes)
`onclick`, `onbeforeunload`
:::spoiler 練習: `按鈕.html`
```htmlembedded=
<button onclick="alert('Hello world!')">
<button id="btn">按鈕</button>
<script>
element = document.getElementById("btn")
element.addEventListener("click", myFunction);
function myFunction() {
alert("Hello World");
}
</script>
```
:::
用HTML寫出一個按鈕([`<button>`](https://www.w3schools.com/tags/tag_button.asp)),使得按下它時出現Hello world
----
## 傳入物件
```javascript= [11-15]
var 某人 = {
暱稱 : 'VJ',
年齡 : 22,
性別 : '男',
興趣 : ['看韓劇', '睡覺', '電腦遊戲'],
高中畢業與否 : true,
打招呼: function() {
alert('Hello world')
}
}
function f(物件){
要印出的 = 物件.性別
alert(要印出的);
}
f(某人)
```
{"breaks":true,"description":"JavaScript教學-110-2主題社課-國立中興大學資訊科學研習社","title":"函式","contributors":"[{\"id\":\"e86b6571-4dea-4aa4-ba20-ece559b0e015\",\"add\":9243,\"del\":5133},{\"id\":\"6d6e3ba2-6820-4c6f-9117-f09bccc7f7aa\",\"add\":1112,\"del\":531}]"}