
- CoffeeScript 教程
- CoffeeScript - 首頁
- CoffeeScript - 概述
- CoffeeScript - 環境
- CoffeeScript - 命令列工具
- CoffeeScript - 語法
- CoffeeScript - 資料型別
- CoffeeScript - 變數
- CoffeeScript - 運算子和別名
- CoffeeScript - 條件語句
- CoffeeScript - 迴圈
- CoffeeScript - 列表推導式
- CoffeeScript - 函式
- CoffeeScript 面向物件
- CoffeeScript - 字串
- CoffeeScript - 陣列
- CoffeeScript - 物件
- CoffeeScript - 範圍
- CoffeeScript - 展開運算子
- CoffeeScript - 日期
- CoffeeScript - 數學
- CoffeeScript - 異常處理
- CoffeeScript - 正則表示式
- CoffeeScript - 類和繼承
- CoffeeScript 高階
- CoffeeScript - Ajax
- CoffeeScript - jQuery
- CoffeeScript - MongoDB
- CoffeeScript - SQLite
- CoffeeScript 有用資源
- CoffeeScript - 快速指南
- CoffeeScript - 有用資源
- CoffeeScript - 討論
CoffeeScript - if 語句
if 語句是基本的控制語句,允許我們根據條件做出決策並執行語句。
CoffeeScript 中的if 語句類似於 JavaScript 中的 if 語句。不同之處在於,在 CoffeeScript 中編寫if 語句時,不需要使用括號來指定布林條件。此外,我們使用適當的縮排分隔條件語句的主體,而不是使用大括號。
語法
以下是 CoffeeScript 中if 語句的語法。它包含一個關鍵字if,緊跟在if 關鍵字之後,我們必須指定一個布林表示式,後面跟一個語句塊。如果給定的表示式為true,則執行if 塊中的程式碼。
if expression Statement(s) to be executed if expression is true
流程圖

示例
以下示例演示如何在 CoffeeScript 中使用if 語句。將此程式碼儲存到名為if_example.coffee的檔案中。
name = "Ramu" score = 60 if score>=40 console.log "Congratulations you have passed the examination"
開啟命令提示符並編譯 .coffee 檔案,如下所示。
c:\> coffee -c if_example.coffee
編譯後,它會生成以下 JavaScript 程式碼。
// Generated by CoffeeScript 1.10.0 (function() { var name, score; name = "Ramu"; score = 60; if (score >= 40) { console.log("Congratulations you have passed the examination"); } }).call(this);
現在,再次開啟命令提示符並執行 CoffeeScript 檔案,如下所示。
c:\> coffee if_example.coffee
執行後,CoffeeScript 檔案會產生以下輸出。
Congratulations you have passed the examination
coffeescript_conditionals.htm
廣告