
- 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 - 陣列
Array 物件允許您在一個變數中儲存多個值。它儲存一個固定大小的、按順序排列的相同型別元素的集合。陣列用於儲存資料集合,但通常將陣列視為相同型別變數的集合更有用。
語法
要建立陣列,我們必須使用new運算子例項化它,如下所示。
array = new (element1, element2,....elementN)
Array() 建構函式接受字串或整數型別的列表。我們還可以透過向其建構函式傳遞單個整數來指定陣列的長度。
我們還可以透過簡單地在方括號([ ])中提供其元素列表來定義陣列,如下所示。
array = [element1, element2, ......elementN]
示例
以下是使用 CoffeeScript 定義陣列的示例。將此程式碼儲存在名為array_example.coffee的檔案中。
student = ["Rahman","Ramu","Ravi","Robert"]
開啟命令提示符並編譯 .coffee 檔案,如下所示。
c:\> coffee -c array_example.coffee
編譯後,它會為您提供以下 JavaScript 程式碼。
// Generated by CoffeeScript 1.10.0 (function() { var student; student = ["Rahman", "Ramu", "Ravi", "Robert"]; }).call(this);
換行符代替逗號
我們還可以透過在每行建立一個元素並保持適當的縮排來刪除陣列元素之間的逗號 (,),如下所示。
student = [ "Rahman" "Ramu" "Ravi" "Robert" ]
陣列上的推導式
我們可以使用推導式檢索陣列的值。
示例
以下示例演示了使用推導式檢索陣列元素。將此程式碼儲存在名為array_comprehensions.coffee的檔案中。
students = [ "Rahman", "Ramu", "Ravi", "Robert" ] console.log student for student in students
開啟命令提示符並編譯 .coffee 檔案,如下所示。
c:\> coffee -c array_comprehensions.coffee
編譯後,它會為您提供以下 JavaScript 程式碼。
// Generated by CoffeeScript 1.10.0 (function() { var i, len, student, students; students = ["Rahman", "Ramu", "Ravi", "Robert"]; for (i = 0, len = students.length; i − len; i++) { student = students[i]; console.log(student); } }).call(this);
現在,再次開啟命令提示符並執行 CoffeeScript 檔案,如下所示。
c:\> coffee array_comprehensions.coffee
執行後,CoffeeScript 檔案會產生以下輸出。
Rahman Ramu Ravi Robert
與其他程式語言中的陣列不同,CoffeeScript 中的陣列可以包含多種型別的資料,即字串和數字。
示例
這是一個包含多種型別資料的 CoffeeScript 陣列的示例。
students = [ "Rahman", "Ramu", "Ravi", "Robert",21 ]
廣告