LESSON-14 · TOPIC 01

Boolean、比較與 if...else

能把比較結果交給 if...else 選出明確分支,不以字串內容猜真假。

code-edit值、條件、scope 與函式責任|Boolean、比較與 if...else本頁只練一個責任

本頁只練什麼

能把比較結果交給 if...else 選出明確分支,不以字串內容猜真假。

價格、庫存與表單狀態若使用錯誤 truthiness,會讓不該通過的輸入進入成功分支。

要修改的檔案:files/starter/main.js

定位:先在 Console 看 typeof total,再看比較式。|依 starter-1 定位,只修改「Boolean、比較與 if...else」的責任。

任務情境

先結果,再原理;完成後要能說出自己看見的證據。

現在的問題

滿額提示把字串 0 誤判成已達門檻。

起始狀態:輸出尚無比較結果與分支。

完成後要看到

comparison=true、branch=eligible,且 inputType=number。

驗收證據:inputType=number、comparison=true、branch=eligible

何時會用到

價格門檻、必填狀態、權限與任何二選一規則。

常見混淆:字串 false 與字串 0 都是 truthy,不等於 Boolean false 或數值 0。

觀念與最小範例

這段程式是理解起點,不是要你直接跳過 Starter。

Boolean、比較與 if...else Boolean comparison and conditional branch

先做出 true/false,再讓 if 決定要走哪一條路。

正式說法:比較運算式產生 Boolean;if 依條件的 truthy/falsy 結果執行互斥 statement branch。

const eligible = total >= 1000;if (eligible) 顯示符合資格。

三步完成本主題

每一步都留下可觀察結果;如果沒看到,先看「卡住先查」。

  1. Step 1|先看見目前缺口,不急著貼答案。

    檔案:files/starter/main.js 定位:先在 Console 看 typeof total,再看比較式。

    要做:先重新載入 Starter,記錄目前畫面、DOM、Computed、Console 或文件內容。

    預期:能指出「先在 Console 看 typeof total,再看比較式。」目前的缺口。

    證據:保存 files/starter/main.js 的目前狀態,並指出下一步只會修改哪個檔案責任。

    卡住先查:確認開啟的是 files/starter/main.js,且定位到 先在 Console 看 typeof total,再看比較式。。

  2. Step 2|只修改本主題的一個責任。

    檔案:files/starter/main.js 定位:先在 Console 看 typeof total,再看比較式。

    要做:以數值輸入執行比較,將 Boolean 交給 if...else 並顯示分支。

    預期:comparison=true、branch=eligible,且 inputType=number。

    證據:inputType=number、comparison=true、branch=eligible

    卡住先查:先在 Console 看 typeof total,再看比較式。

  3. Step 3|重新載入並以證據驗收,不以『看起來差不多』判定完成。

    檔案:files/starter/main.js 定位:先在 Console 看 typeof total,再看比較式。

    要做:重新整理頁面,再逐項比對預期結果與 evidence。

    預期:comparison=true、branch=eligible,且 inputType=number。

    證據:inputType=number、comparison=true、branch=eligible

    卡住先查:先在 Console 看 typeof total,再看比較式。

觀察示範

這個示範只讓你看懂概念,不會替你修改 Starter,也不會自動宣告完成。

Boolean、比較與 if...elseruntime fixture · read-only demo
本主題示範畫面:
尚未比較

驗收證據

勾選只是學習紀錄;真正完成仍要回到 Starter 的實際結果。

提示 1|方向

把轉型、比較、分支拆成三步。

提示 2|關鍵片段

先求 total >= threshold,再把結果交給 if。

提示 3|完整解答與原因

完整解答與原因:將 total 與 threshold 都視為 number,計算 total >= threshold 得到 Boolean,再由 if...else 選 eligible;因為分支應依明確比較而非字串 truthiness。

完成後進入下一階段,或回到入口選下一個 topic。

開始 Starter →回到主題清單