
- 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和unless一樣,CoffeeScript也提供了推導式的字尾形式,這在編寫程式碼時非常方便。使用它,我們可以將for..in推導式寫成一行程式碼,如下所示。
#Postfix for..in comprehension console.log student for student in ['Ram', 'Mohammed', 'John'] #postfix for..of comprehension console.log key+"::"+value for key,value of { name: "Mohammed", age: 24, phone: 9848022338}
字尾形式的for..in推導式
以下示例演示了CoffeeScript提供的for..in推導式的字尾形式的用法。將此程式碼儲存在名為for_in_postfix.coffee的檔案中。
console.log student for student in ['Ram', 'Mohammed', 'John']
開啟命令提示符並編譯.coffee檔案,如下所示。
c:\> coffee -c for_in_postfix.coffee
編譯後,它會生成以下JavaScript程式碼。
// Generated by CoffeeScript 1.10.0 (function() { var i, len, ref, student; ref = ['Ram', 'Mohammed', 'John']; for (i = 0, len = ref.length; i < len; i++) { student = ref[i]; console.log(student); } }).call(this);
現在,再次開啟命令提示符並執行CoffeeScript檔案,如下所示。
c:\> coffee for_in_postfix.coffee
執行後,CoffeeScript檔案會產生以下輸出。
Ram Mohammed John
字尾形式的for..of推導式
以下示例演示了CoffeeScript提供的for..of推導式的字尾形式的用法。將此程式碼儲存在名為for_of_postfix.coffee的檔案中。
console.log key+"::"+value for key,value of { name: "Mohammed", age: 24, phone: 9848022338}
開啟命令提示符並編譯.coffee檔案,如下所示。
c:\> coffee -c for_of_postfix.coffee
編譯後,它會生成以下JavaScript程式碼。
// Generated by CoffeeScript 1.10.0 (function() { var key, ref, value; ref = { name: "Mohammed", age: 24, phone: 9848022338 }; for (key in ref) { value = ref[key]; console.log(key + "::" + value); } }).call(this);
現在,再次開啟命令提示符並執行CoffeeScript檔案,如下所示。
c:\> coffee for_of_postfix.coffee
執行後,CoffeeScript檔案會產生以下輸出。
name::Mohammed age::24 phone::9848022338
coffeescript_comprehensions.htm
廣告