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 New
    • 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 Note Insights 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

    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
    # <font class="h2">控制判斷if 、 switch</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> :arrow_right:[MDN資料](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Expressions_and_Operators) ### <font class="h3">if 、 else 、 else if</font> ```javasript if(條件式) {陳述句;} ``` 條件式運算結果為`true`會執行if的`{}`中的陳述句,否則執行`else`的`{}`中的陳述句,如果條件式不成立時並不想作任何事,則`else`可以省略。 - `if`、`else`只能一組、`else if`可以多組 - 最後不一定要加else,可以只使用到`if` - if 常用在 「如果」、「假如」、「是否」、判斷的情境上 :::info **if範例** ```javascript //小美在氣溫15度以下時一定會穿上她心愛的棉外套 //今天氣溫是14度,請試著用if來寫小美會寫如何行動 //小美穿這外套出門了 let todayDegrees = 14; let isWearJacket = 15 >= todayDegrees; if(15 >= todayDegrees){ console.log("小美穿這外套出門了") console.log("他準備出門了") } //(15 >= todayDegrees)為條件式如果是true的話,就會執行{}裡的內容 ``` ```javascript if(ture){ //也可以這樣寫,只接寫true console.log("小美穿這外套出門了") console.log("他準備出門了") } ``` ```javascript if(isWearJacket){ //也可以這樣寫 console.log("小美穿這外套出門了") console.log("他準備出門了") } ``` ::: :::info **else範例** ```javascript let todayDegrees = 20; let isWearJacket = 15 >= todayDegrees; if(15 >= todayDegrees){ console.log("小美穿這外套出門了") console.log("他準備出門了") }else{ console.log("小美因為太熱,所以不穿外套")//小美因為太熱,所以不穿外套 } //如果if條件不滿足,就會去執行else ``` ::: :::info **else if範例** ```javascript //小明想要去外面吃飯,他很想吃牛肉麵,價格為110 //但他不確定錢包剩下多少錢 //有80元,他就去吃夜市牛排 //有35元,他就會跑去吃薯條 //於是他打開錢包前決定,錢不夠就回家吃飯 let wallet = 80; if(wallet>=110){ console.log("小明跑去吃牛肉麵") }else if(wallet>= 80){ console.log("小明跑去吃夜市牛排了")//小明跑去吃夜市牛排了 }else if(wallet>=35){ console.log("小明跑去吃薯條了!") }else{ console.log("小明錢不夠,跑回家吃飯了") } ``` ::: <br> ### <font class="h4">流程圖 </font> * [流程圖](https://zh.wikipedia.org/wiki/%E6%B5%81%E7%A8%8B%E5%9B%BE)介紹 ![](https://i.imgur.com/3Pj4fvz.png)[(圖片來源)](https://ithelp.ithome.com.tw/articles/10271176) * [whimsical](https://whimsical.com/4oYtsHWjADWsieeNrjY1Xa)繪圖服務 遇到問題時 步驟一:任務拆解 步驟二:流程設計 **範例一:** ```javascript //小華他想出門,但他不確定自己的錢包有多少錢 //於是他打開錢包看看還有多少錢 //打開後,他發現有150元,於是他就紀錄在腦袋裡,他擁有150元 ``` :arrow_right:[畫流程圖](https://whimsical.com/Aqeor3e7d3AXauzss1vm5) ```javascript let wallet = 0; wallet+=150; console.log('小華錢包還有${wallet}元`)'); ``` <br> **範例二:** ```javascript //小華他想出門,但他不確定自己的錢包有多少錢 //於是他打開錢包看看還有多少錢 //如果小華發現自己有100元,他就吃80元牛肉麵 //如果沒有100元,就不吃任何東西,也不出門 //最後小華還想計算自己最後剩下多少錢元 ``` :arrow_right:[畫流程圖](https://whimsical.com/WL65R22E41cFyjgeWKxFYq) ```jav![Uploading file..._n4aosabm6]() ascript let wallet = 0; wallet+=150; if(wallet>=100){ wallet-=80 }else{ wallet-=0 } console.log(`小華錢包還有${wallet}元`); ``` <br> :::info **if包if範例** ```javascript //腰圍指數測量 //男生腰圍大於90為過胖 //女生腰圍大於80為過胖 1.先判斷男生是女生 2.如果是男生,還得判斷他的腰圍,90為過胖 3.如果是女生,還得判斷她的腰圍,80為過胖 ``` [畫流程圖](https://whimsical.com/if-if-5dPJGxv9caRDjLX7VT32pP) ```javascript let sex = "male"; let cm = 88; if(sex =="male"){ if(cm>=90){ console.log("男生體型過胖") }else{ console.log("男生體型正常") } }else if(sex =="woman"){ if(cm>=80){ console.log("女生體型過胖") }else{ console.log("女生體型正常") } }else{ console.log("您的資料錯誤") } ``` ::: :::spoiler 範例 - 例一. ```javascript 小華他的習慣是 1.如果沒有下雨,就不會帶雨具 2.但如果下毛毛雨,他會帶輕便雨衣 3.假使下普通的雨,他會帶折傘 4.如果颱風天豪雨,他會帶常傘 今天是毛毛雨,那小華會帶什麼雨具? let todayWeater = "毛毛雨": if(todayWeater=="沒有下雨"){ console.log("小華不帶雨具"); }else if(todayWeater=="毛毛雨"){ //帶了輕便雨衣 console.log("帶了輕便雨衣") }else if(todayWeater=="普通的雨"){ console.log("帶了折傘") }else if(todayWeater=="颱風豪雨"){ console.log("帶長傘") }else{ console.log("小華遇到異常狀態") } console.log("小華出門了")//小華出門了 ``` - 流程圖範例-觀察客戶體溫. ```javascript let myDegree =30; if(myDegree>=37.5){ console.log("您不得進入") }else{ console.log("您可以請進入") } ``` - 流程圖範例-計算小明成績是否及格. ```javascript let myScore=59; if(myScore>=60){ console.log("您的成績及格"); }else{ console.log("您的成績不及格"); } ``` - 流程圖範例-計算小明成績. ```javascript let myScore = 90; if (myScore>=80){ console.log("優秀") }else if(myScore>=60 && 79>=myScore){ console.log("普通") }else if(59>=myScore){ console.log("不及格") }else{ console.log(輸入數值不正確) } ``` - 直播範例一-小華是否能去遊樂園 小華考了國英數,國文考 10 分、英文考 60 分、數學考 200 分,他想起父親告訴他,如果他總分有達 240 分,就帶他去遊樂園,快來幫忙算算他是否有達到門檻 ```javascript let chScore =0; let maScore =0; let enScore =0; let total =0; //先設定預設值 chScore =10; maScore =200; enScore =60; total =chScore+maScore+enScore; if(total>=240){ console.leg('帶你去遊樂園') } ``` - 直播範例二-小美快樂指數 小美為了讓自己快樂,內心有個快樂指數,範圍是 0~10,10 是最快樂。當小美指數在 8 (含)以上時,會選擇宅在家,指數在 5~7 時會選擇去血拼,在 4(含) 以下時,會選擇跟人去唱卡拉ok。小美今天的快樂指數為 6,那麼他會想做什麼事呢? ```javascript let happyScore = 0; happyScore =6; if(happyScore>=8){ console.log("宅在家") }else if(happyScore>=5 && happyScore<=7){ console.log("血拚") }else if(happyScore<=4){ console.log("唱歌") } ``` - 直播範例三-小明參加歌手牽手會 小明去參加歌手牽手會,到門口時,守衛問他說,有沒有帶入場券,小明亮出入場券後進入了會場,隨後想排隊跟歌手牽手時,又被第二個守衛擋住,問他說,他有沒有買 5000 張以上 DVD?但因為小明只有買 3000 張 DVD,小明只好忍痛離開,並下定決心要將這過程記錄下來,下次一定要握到手! ```javascript let isTicket = true; let DVDNum = 3000; if(isTicket==true){ if(DVDNum>= 5000){ console.log("ya 握到手!!!") } } ``` 也可以邏輯運算值寫法 ```javascript let isTicket = true; let DVDNum = 3000; if(isTicket==true && DVDNum>=5000){ console.log("握到手了,YA"); }else{ console.log("沒有握到手哭哭T_T"); } ``` ::: <br> ### <font class="h3">switch</font> :arrow_right:[if 與 switch 的使用時機?](https://hackmd.io/VMw-qqfRRXKkhG4yLQ_m6A?view) - 輸入值可以是變數,也可以是表達式,只要得出的值有辦法對應比對值就可以了 - 輸入值 與 比對值必須全等`===`才行,屬於嚴格比對! - `break` 通常情況下會加上去,不然判斷不會自己中斷,會從比對成功的程式碼一路執行下去,直到碰到 `break` - `default `主要功能是,當條件都沒辦法達成時,會執行這段,與 else 一樣不一定要添加,一個 switch 只能使用一個 :::info ```javascript const seasonType = Math.ceil( month / 3 );//Math.ceil向上取整,有小數就整數部分加1 if ( seasonType === 1) { console.log('春天'); } else if ( seasonType === 2) { console.log('夏天'); } else if ( seasonType === 3) { console.log('秋天'); } else if ( seasonType === 4) { console.log('冬天'); } else { console.log('月份錯誤'); } ``` 改成switch ```javascript switch ( Math.ceil( month / 3 ) {//輸入值 case 1: // 比對值,如果是1的話執行 console.log('春天'); // 輸入值 與 比對值 "全等"才會執行這段 break; // 中斷判斷跳出 case 2: console.log('夏天'); break; case 3: console.log('秋天'); break; case 4: console.log('冬天'); break; default: console.log('月份錯誤'); break; } ``` ::: 同時使用多個條件 case 的方法 ```javascript var Animal = 'Giraffe'; switch (Animal) { case 'Cow': case 'Giraffe': case 'Dog': case 'Pig': console.log('This animal will go on Noah\'s Ark.'); break; case 'Dinosaur': default: console.log('This animal will not.'); } ``` <br> ### <font class="h3">switch作條件判斷</font> :::info case 中可以使用運算式,因 JavaScript 是直譯式語言,執行時才會進行運 算,編譯式語言在編譯時無法運算結果。 ::: ![](https://i.imgur.com/wZqlDPU.png) ![](https://i.imgur.com/BUmkbSI.png) <br><br><br><br> ### <font class="h3">可以設置預設值default</font> ```javascript switch ("Mark") { case "Mark": console.log("Mark"); break; case "John": console.log("John"); break; default: console.log("Other"); } ```

    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