目录

CoffeeScript - 数组( Arrays)

Array对象允许您在单个变量中存储多个值。 它存储固定大小的相同类型元素的顺序集合。 数组用于存储数据集合,但将数组视为相同类型的变量集合通常更有用。

语法 (Syntax)

要创建数组,我们必须使用new运算符对其进行实例化,如下所示。

array = new (element1, element2,....elementN)

Array()构造函数接受字符串或整数类型的列表。 我们还可以通过将一个整数传递给它的构造函数来指定数组的长度。

我们还可以通过简单地在方括号( [ ] )中提供其元素列表来定义数组,如下所示。

array = [element1, element2, ......elementN]

例子 (Example)

以下是在CoffeeScript中定义数组的示例。 将此代码保存在名为array_example.coffee的文件中

student = ["Rahman","Ramu","Ravi","Robert"]
<p></p>

打开command prompt并编译.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"
  ]

对数组的理解

我们可以使用理解来检索数组的值。

例子 (Example)

以下示例演示了使用理解检索数组的元素。 将此代码保存在名为array_comprehensions.coffee的文件中

students = [ "Rahman", "Ramu", "Ravi", "Robert" ]
console.log student for student in students 

打开command prompt并编译.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);

现在,再次打开command prompt并运行CoffeeScript文件,如下所示。

c:\> coffee array_comprehensions.coffee

执行时,CoffeeScript文件生成以下输出。

Rahman
Ramu
Ravi
Robert

与其他编程语言中的数组不同,CoffeeScript中的数组可以有多种类型的数据,即字符串和数字。

例子 (Example)

以下是包含多种类型数据的CoffeeScript数组的示例。

students = [ "Rahman", "Ramu", "Ravi", "Robert",21 ]
<p></p>
↑回到顶部↑
WIKI教程 @2018