tingtinghsu
    • 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
    • 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
    • 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 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
  • 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
    --- title: javascript 6.4 函數 function tags: javascript, 5x --- 6.4 0313 javascript 函數 function === # 1. function: 重複利用的SOP ## 跟客人打招呼: ```javascript= function sayHelloTo(customer) { console.log('Hi! ' + customer); } sayHelloTo('孫小美'); sayHelloTo('錢夫人'); sayHelloTo('阿土伯'); ``` 輸出: ```htmlmixed "Hi! 孫小美" "Hi! 錢夫人" "Hi! 阿土伯" ``` fuction名字: sayHelloTo 代入參數: customer function裡面:做的事`(跟客人打招呼)` ```javascript function sayHelloTo(customer) { console.log('Hi! ' + customer); } ``` 就算有SOP,仍必須主動做出`跟客人打招呼`這件事: ```javascript sayHelloTo('客人的名字'); /*執行定義好的function,並代入字串*/ ``` # 2. function 內加上條件判斷 eg. 檢查年齡 ## 寫法1. 呼叫多次函數 ```javascript= function isAdult(age) { if(age >= 18) { console.log(age+'歲,可以喝酒了!'); } else console.log(age+'歲,好年輕呀!'); } isAdult(17); isAdult(18); ``` 輸出: ```htmlmixed "17歲,好年輕呀!" "18歲,可以喝酒了!" ``` ## 寫法2. 換成使用者輸入的版本: ```javascript var age = prompt('請輸入年齡'); function isAdult(age) { if(age >= 18) { console.log(age+'歲,可以喝酒~'); } else console.log(age+'歲,好年輕呀!'); } isAdult(age); ``` 輸出 ```javascript "15歲,好年輕呀!" "33歲,可以喝酒~" ``` ## 寫法3. 與true / false結合,傳出參數 因為console.log功能不包含回傳, (只負責印出內容,但是回傳值是undefined) 所以我們寫一個function,用true明確的回傳結果。 ```javascript /*function + 包含true / false 條件判斷先寫好*/ function isAdult(age) { if(age >= 18) { return true; } else { return false; } } /*if true,條件判斷*/ var yourAge = 18; if (isAdult(yourAge)) { /*如果為True*/ console.log(yourAge+'歲,可以喝酒了!'); } else { console.log(yourAge+'歲,好年輕呀!'); } ``` ## 寫法4. 寫法3進化版: 使用者輸入的版本 ```javascript= /*function + 包含true / false 條件判斷先寫好*/ function isAdult(age) { if(age >= 18) { return true; } else { return false; } } /*if true,條件判斷*/ var yourAge = prompt('請輸入你的年紀:'); if (isAdult(yourAge)) { /*如果為True*/ console.log(yourAge+'歲,可以喝酒了!'); } else { console.log(yourAge+'歲,好年輕呀!'); } ``` # 3. function的 return回傳值 用console的方式,雖然能夠在螢幕上顯示出來,但沒有回傳值。 ```bash > console.log(`hi`) hi < undefined > function abc() { return 100 } < undefined > abc () < 100 ``` ## 寫法五: 簡潔的function定義方法 ```javascript= function isAdult(age) { if(age >= 18) { return true; } else { return false; } } ``` 等於 ```javascript= function isAdult(age) { if(true) { return true; } /*true重複,多餘邏輯*/ else { return false; } } ``` 等於 ```javascript= function isAdult(age) { return (age >= 18); } ``` # 4. anonymous function匿名函數 ## 寫法六: 改為匿名函數 ```javascript= function isAdult(age) { return (age >= 18); } ``` 改為沒有名字的function: ```javascript= var isAdult = function(age) { return (age >= 18); ``` ## 匿名與非匿名比較 ```javascript= function a1() { console.log('a1'); } a2 = function() { console.log('a2'); } a1(); a2(); ``` 輸出: ```bash "a1" "a2" ``` ## Hoisting 變數提升 javascript會自動做變數提升,用var設定變數, 在一些情況下會呼叫不到。 ```javascript= /* var abc, a2; java根據下面程式設定abc與a2變數*/ function a1() { console.log('a1'); } a2 = function() { console.log('a2'); } a1(); a2(); var abc = 123; ``` 如果把`a1()`, `a2()` 提到前面: ```javascript= a1(); // javascript會把變數提升 => var a2; // undefined a2(); var abc, a2; function a1() { console.log('a1'); } a2 = function() { console.log('a2'); } var abc = 123; ``` 執行時會出現問題 ```bash "a1" "error" "TypeError: a2 is not a function at delobel.js:2:1 at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924 at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866" ``` # hello 和 hello() 的不同 hello是function, hello()是執行函數的結果。 ## 有回傳值的結果 ```javascript function hello() {} undefined function hello() {console.log('hi');} undefined > hello() hi VM150:1 undefined > hello ƒ hello() {console.log('hi');} ``` ## 沒有回傳值的結果 ```javascript function hello_return() {return 1}; undefined hello_return(); 1 hello_return; ƒ hello_return() {return 1} ``` # BMI練習題,使用funtion改寫 ```javascript function bmiResult(height, weight) { // } ``` 解法: ```javascript function bmiResult(height, weight) { bmi = weight / ( height * height ) return bmi; } var height = prompt('請輸入你的身高(公尺):'); var weight = prompt('請輸入你的體重(公斤):'); console.log( bmiResult(height, weight) ); ``` # 閏年練習題,使用funtion改寫 ```javascript function isLeapYear(year) { } ``` 解法: ```javascript function isLeapYear(year) { if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)){ return true; } else return false; } var year = prompt('請輸入年份'); if (isLeapYear(year)) { console.log( year +'年是閏年'); } else { console.log( year +'年不是閏年'); } ``` 輸出: ```javascript "1980年是閏年" "1990年不是閏年" "2000年是閏年" ```

    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