NCU NKFW
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 函式(Function) ###### tags: `NKFW 網頁設計入門` --- ## 介紹 假設我們需要寫一段程式碼輸出三次"Hello",按照前面學過的內容,應該會寫出類似底下的程式: ```javascript! alert("Hello"); alert("Hello"); alert("Hello"); ``` --- 但在借助函式的幫助下,我們可以將其改為底下的這個程式: ```javascript! function hello() { alert("Hello"); } hello(); hello(); hello(); ``` 上方的程式可以達到同樣的目標。 --- * alert()其實就是一個Javascript內建的函式! ![](https://hackmd.io/_uploads/Byp8aaerh.png) --- ## 優點 * 減少寫作功能相同或相似的程式。 * 增加主要程式的易讀性。 * 易於除錯及修改程式。 --- ## 定義(Define)及呼叫(Call) 使用一個函式前必須先將其定義,定義函式的基本語法如下: ```javascript! function 函式名稱() { //執行動作/程式 } ``` 在程式中輸入"函式名稱();"即可呼叫函式,並執行函式中所撰寫的程式。 ```javascript! 函式名稱(); ``` --- ## 參數(Parameter) * 呼叫函式時,同時提供資料給函式以執行所需功能。 ```htmlembedded function hello(name) { alert("Hello, " + name + "."); } ``` 在撰寫上方函式後,即可透過給予函式資料來達到想要的效果,例如: ```htmlembedded hello("John"); hello("Mark"); ``` --- 執行程式後得到底下兩張圖的結果: ![](https://i.imgur.com/pSdrmdx.png) ![](https://i.imgur.com/Va6gmHa.png) --- 函式的參數可超過一個,例如下方程式: ```htmlembedded! function hello2(name1, name2) { alert("Hello, " + name1 + " and " + name2 + "."); } hello2("John", "Mark"); ``` 可得下圖結果: ![](https://i.imgur.com/tBuZTa8.png) --- ## Project1:單位轉換 :::info 單位轉換在物理計算中相當重要,透過適當的單位轉換才能夠符合公式的單位要求。 請設計一個函式centiToMeter,可以接收1個數字,其單位視為公分,在將單位轉為公尺後輸出其數字部分。 主要程式的部分則是以跳出視窗(prompt)讓使用者輸入數字,並將數字遞給函式輸出結果。 ::: --- :::spoiler 參考答案 ```htmlembedded! function centiToMeter(centimeter) { alert("長度為" + centimeter/100 + "m"); } length = prompt("請輸入長度(cm):") centiToMeter(length); ``` ::: --- ## 回傳(Return) 函式的功能並不只有執行動作(如alert),我們也可以透過將函式的運算結果回傳主要程式並儲存下來,更方便的做單次或多次的運用。 例如,我們可以將Project1的程式重寫為底下的形式,並保留原本執行效果: ```htmlembedded! function centiToMeter(centimeter) { return centimeter/100; } meter = centiToMeter(150); alert(meter); ``` --- ## Project2:圓形面積 :::info 一般在計算圓形面積時,我們需要用到pi值及圓的半徑,並可透過「PI * 半徑^2」的公式計算。 請用函式的寫法設計一段程式,可透過給予函式圓形半徑,計算出圓形面積並回傳結果至主程式。 (PI使用3.14替代即可) ::: --- :::spoiler 參考答案 ```htmlembedded! function circleArea(radius) { PI = 3.14; return PI * radius**2; } ``` ::: --- ## Project3:計算BMI :::info 透過prompt()讓使用者輸入兩個數字,分別是身高和體重,並將他們傳入函式中,並在計算後回傳相應的BMI值,輸出給使用者觀看。 ::: --- :::spoiler 參考答案 ```javascript! function calculateBMI (h, w) { return w / (h / 100) ** 2; } let height = prompt("Please enter your height(cm): "); let weight = prompt("Please enter your weight(kg): "); alert(calculateBMI(height, weight)); ``` ::: --- ## setTimeOut函式 * setTimeOut是一個Javascript內建的function,可以使程式在等待特定毫秒數後,執行指令。 * setTimeOut一共接受兩個輸入,依次分別是1個函式及1個數字。 範例如下: ```htmlembedded! setTimeout(function() { alert("hello"); },3000); ``` --- ![](https://i.imgur.com/bkArGmD.png) 此程式執行3秒後才會得到圖中結果。 --- * 範例中「function() {......}」的使用法稱為anonymous function(匿名函式),通常用於只執行一次的function,因此不必給予函式名稱。 <!-- * 範例中,我們透過使用setTimeOut()來呼叫輸入的function(),這種透過函式呼叫函式的方式在Javascipt中稱作callback function。 --> * 範例中,我們將匿名函式做為setTimeOut()函式的輸入,此時我們將此匿名函式稱作callback function。 > [[參考說明](https://www.w3schools.com/js/js_callback.asp)] --- :::info 進階寫法: 運用Arrow function(箭頭函式)的方式撰寫輸入setTimeOut()的函式(Arrow function也屬於anonymous function)。 ``` setTimeout( () => {alert(10)}, 3000 ); ``` ::: --- # setInterval,clearInterval函式 ### 基本語法: ```javascript= setInterval(function,delay); ``` * function:要重複執行的功能 * delay:每次執行的間隔時間 ```javascript= clearInterval(Interval variable) ``` * 停止迴圈 --- ### 範例說明: ```htmlembedded! let repeat = setInterval(function(){ alert("hello"); },2000); setTimeout(() => { alert("stop"); clearInterval(repeat); }, 6000); ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully