grayshine
    • Create new note
    • Create a note from template
      • 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
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me 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
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control 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
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # <font class="h2">函式是什麼?</font> ###### tags: `javascript` <style> .h2 { background: linear-gradient(135deg,#fff,#537479) ; color: #537479; display:block; padding: 6px 5px; border-radius: 4px; } .h3 { background: linear-gradient(180deg,#fff 50%,#c9d5d4) ; color: #537479; display:block; padding: 6px 5px; border-bottom: 3px solid #537479; } .h4 { color: #537479; font-weight:bold; font-size:1.1em; } </style> <br> ![](https://i.imgur.com/n2fCBn8.jpg =500x) 「函式」指的是將一或多段程式指令包裝起來,可以==重複使用,消除重複性==也方便維護。 :::info 輸入→編譯(函式)→輸出 ::: <br> ### <font class="h4">➤執行函數</font> ```javascript function greet(){ console.log('歡迎光臨!') console.log('請問你要點些什麼?') } // function為宣告函式,greet為函式名稱 greet(); //執行函式得到解果 ``` 如果指令很重複,就可以利用函式再帶函式去執行 ```javascript function morningAction(){ console.log("起床"); cleanHead(); console.log("睡覺"); } function nightAction(){ console.log("回家"); cleanHead(); console.log("睡覺"); } function cleanHead(){ console.log("刷牙"); console.log("洗臉"); } morningAction();//"起床""刷牙""洗臉""出門" ``` <br> ### <font class="h4">➤函式參數</font> 範例一: ```javascript function a(num){ console.log(num); } a(1)//1 ``` 範例二-兩個數字相加小工具: ```javascript function count(oneNum,twoNum){ let total = oneNum +twoNum; console.log("總價格:"+total+"元") } count(8,2); //帶入值得到結果 ``` <br> ### <font class="h3">回傳return</font> 回傳是將「控制權」從函數轉移到其「呼叫方」 return可以回傳值,也可以回傳物件 :::info :bulb:參數只會存活在大括號裡 ```javascript function calcTotalScore(chineseScore,mathScore){ console.log(chineseScore+mathScore); } let markTotalScore =calcTotalScore(40,60); console.log(markTotalScore);//undefined ``` 使用return ```javascript function calcTotalScore(chineseScore,mathScore){ return chineseScore + mathScore; } let markTotalScore =calcTotalScore(40,60); console.log(markTotalScore);//100 ``` ::: 範例: ```javascript function getHamPrice(num){ let hamPrice = 50; let total = hamPrice * num; return total; } var tom = getHamPrice(10); console.log(tom);//得到值為500 ``` :::info **return與console.log的差異** - return回來的值,我們是可以做運用的,有實際的控制權。如果我們需要對function所回傳的值做後續的處理,那麼就必須要return回傳值。 - console.log比較像是查看狀態,檢視(印出)我們想知道的環節、輔助我們debug ::: <br> ### <font class="h4">➤return 可以有多個</font> :::info :bulb:return可以中斷函式執行,後面的程式就不跑了 ::: ```javascript function calcTotalScore(chineseScore,mathScore){ let totalScore = chineseScore + mathScore; return totalScore; console.log('hello')//第一個return之後的程式都不會跑 return 3; } let tomTotalScore = calcTotalScore(100,100); console.log('Tom的總分為${tomTotalScore}'); ``` return 可以有多個範例 ```javascript function checkScore(score){ if(score >= 60){ return'及格'; }else{ return'不及格'; } } let tomScore = checkScore(60); console.log(tomScore); ``` 範例-偶數判斷: ```javascript function checkNumber(myInput){ if(myInput%2 == 0){ return"是偶數"; }else{ return"不是偶數" } } let checkSevenNumber = checkNumber(7); console.log(checkSevenNumber) ``` <br> ### <font class="h4">➤所有函式一定會回傳值</font> 所有函式一定會回傳值,沒有return的話還是會傳undefined ```javascript var a = { name: 'a' } function changeData(param) { param.name = 'b' } var b = changeData(a) console.log(b) //undefined ``` ### <font class="h3">let 全域與區域變數</font> :arrow_right:[範圍鍊](https://hackmd.io/@grayshine/SJx6xzlDt) 如果內層找不到變數可以使用,就會向外查找 ![](https://i.imgur.com/alJSSY7.png =300x) <br> 計算次數功能範例 ```javascript let count = 0; function test(){ count+=1; } test(); console.log(`目前您紀錄了${count}次`)//1 ``` ```javascript let c =4; function numAdd(a,b){ let c =3; console.log(c); } console.log(c);//4,let宣告的變數作用域在區塊作用域內,外面讀不到 ``` :::info ```javascript function fn(){ a = 0; } console.log(a); //會得到a為0 ``` ```javascript let c = 4; function numAdd(a,b){ c =10; } console.log(c);//4 ``` 沒宣告的話,會是全域「屬性」 :bulb:沒有宣告的話,會造成全域汙染,變得髒。要盡可能去宣告變數 ::: <br> :::info ```javascript let c = 4; function fn(){ let c = 2//2會被8覆蓋 c = 8; } console.log(c);//4 ``` :bulb:先找碗內,再找碗外 ::: <br> ### <font class="h4">➤範例</font> **範例一_字串相加** ```javascriopt //input talk("早上好"); talk("晚上好"); // output // "hi,早上好" // "hi,晚上好" ``` :::spoiler ```javascript function talk(message){ console.log('hi',message); } talk("早上好"); talk("晚上好"); ``` ::: <br> **範例二_數字處理** ```javascript let data = 0; //input count(2); count(3); count(5); // output //2 //5 //10 ``` :::spoiler ```javascript let data = 0; function count(num){ data+=num; console.log(data); }; count(2); count(3); count(5); //函數可以幫外部(全域)去累加資料 ``` ::: <br> **範例三_數字** ```javascript //input count(2); count(3); count(5); // output // 4 // 9 //25 ``` :::spoiler ```javascriopt ``` ::: <br> **範例四_兩位數四舍五入** ```javascript twoFixed(1.8888) twoFixed(3.1234) // output // 1.89 // 3.13 ``` :::spoiler ```javascript function twoFixed(num){ console.log(num.toFixed(2)); } twoFixed(1.8888) twoFixed(3.1234) ``` ::: <br> **範例五_BMI** ```javascriopt calcBmi(178,69) //output //21.78 ``` :::spoiler ```javascript //BMI = 體重(公斤) / 身高2(公尺2) function calcBmi(height,weight){ let bmi = weight/(height/100)**2; console.log(bmi.toFixed(2)); } calcBmi(178,69) ``` ::: <br> **範例六_檢查是否需要帶雨具+if** ```javascript checkWeater("雨天"); // 要帶雨具 checkWeater("晴天"); //不用帶雨具 ``` :::spoiler ```javascript function checkWeater(weather){ if(weather == "雨天"){ console.log("要帶雨具"); } else if (weather == "晴天"){ console.log("不用帶雨具"); }; }; checkWeater("雨天"); // 要帶雨具 checkWeater("晴天"); //不用帶雨具 ``` ::: <br> **範例七_增加陣列資料** ```javascript let data = []; add("hello"); add("你好嗎?"); // output // ["hello","你好嗎?"] ``` :::spoiler ```javascript let data = []; function add(str){ data.push(str) console.log(data); } add("hello"); add("你好嗎?"); ``` ::: **範例八_增加陣列物件資料** ```javascript let data = []; add("洧杰","男生"); add("葉子","女生"); // output //[ // {name:"洧杰",sex:"男生"}, // {name:"葉子",sex:"女生"} //] ``` :::spoiler ```javascript let data = []; function add(name,sex){ let obj = {}; obj.name = name; obj.sex = sex data.push(obj); console.log(data); } add("洧杰","男生"); add("葉子","女生"); ``` ::: <br> **範例九_取物件資料** ```javascriopt const bmiStatesData = { "overThin": { "state": "過輕", "color": "藍色" }, "normal": { "state": "正常", "color": "紅色" } } checkBmiStates("overThin"); //你的體重過輕,指數為藍色 checkBmiStates("normal"); //你的體重正常,指數為紅色 ``` :::spoiler ```javascript const bmiStatesData = { "overThin": { "state": "過輕", "color": "藍色" }, "normal": { "state": "正常", "color": "紅色" } } function checkBmiStates(str){ body = bmiStatesData[str]; console.log() console.log(`你的體重${body.state},指數為${body.color}`); } checkBmiStates("overThin"); checkBmiStates("normal"); ``` :::

    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