目录

CoffeeScript - 快速指南

CoffeeScript - Overview

目前,JavaScript是目前最快的主流动态语言,它被称为网络的lingua franca 。 它由Brendan Eich在1995年开发,为期10天。

由于其有效的功能,JavaScript变得流行并迅速走向全球。 它在实验室里的时间要少得多,这还不足以改善语言。 可能是因为这个原因,尽管它有很好的部分,但JavaScript有一堆设计错误,并且它成为一种古怪语言的坏名声。

什么是CoffeeScript?

CoffeeScript是一种基于Ruby和Python的轻量级语言,可以transcompiles (从一种源语言编译到另一种源语言)转换为JavaScript。 它提供了更好的语法,避免了JavaScript的古怪部分,仍然保留了语言的灵活性和美感。

CoffeeScript的优点

以下是CoffeeScript的优点 -

  • Easily understandable - CoffeeScript是JavaScript的简写形式,与JavaScript相比,它的语法非常简单。 使用CoffeeScript,我们可以编写干净,清晰且易于理解的代码。

  • Write less do more - 对于JavaScript中的大量代码,我们需要相对少量的CoffeeScript行。

  • Reliable - CoffeeScript是一种安全可靠的编程动态程序编程语言。

  • Readable and maintainable - CoffeeScript为大多数操作符提供别名,使代码可读。 使用CoffeeScript编写程序也很容易。

  • Class-based inheritance - JavaScript没有类。 而不是它们,它提供了强大但令人困惑的原型。 与JavaScript不同,我们可以在CoffeeScript中创建类并继承它们。 除此之外,它还提供实例和静态属性以及mixins 。 它使用JavaScript的原生原型来创建类。

  • No var keyword - 不需要使用var关键字在CoffeeScript中创建变量,因此我们可以避免意外或不需要的范围减速。

  • Avoids problematic symbols - 不需要在CoffeeScript中使用有问题的分号和括号。 我们可以使用空格来区分块代码,如函数,循环等,而不是花括号。

  • Extensive library support - 在CoffeeScript中,我们可以使用JavaScript库,反之亦然。 因此,在使用CoffeeScript时,我们可以访问一组丰富的库。

CoffeeScript的历史

  • CoffeeScript由Jeremy Ashkenas开发。 它于2009年12月13日首次在Git中发布。

  • 最初,CoffeeScript的编译器是用Ruby语言编写的。

  • 2010年3月,CoffeeScript编译器被替换; 这次他们使用的是CoffeeScript,而不是Ruby。

  • 同年,CoffeeScript 1.0发布,在发布时,它是Git中心最受欢迎的项目之一。

CoffeeScript的局限性

  • Sensitive to whitespaces - CoffeeScript Sensitive to whitespaces非常敏感,因此程序员在提供缩进时需要非常小心。 如果我们没有保持适当的缩进,整个代码可能会出错。

IoWiki的CoffeeScript IDE

您可以使用我们的Coding Ground部分http://www.iowiki.com/codingground.htm提供的IoWiki的CoffeeScript编译器编译CoffeeScript文件。 按照下面给出的步骤使用我们的CoffeeScript编译器。

Step 1

点击以下链接www.iowiki.com访问我们网站的www.iowiki.com

Step 2

单击位于主页右上角的名为CODING GROUND的按钮,如下面给出的快照中突出显示的那样。

iowiki主页

Step 3

这将导致我们的CODING GROUND部分为大约135种编程语言提供在线终端和IDE。 在“在线IDE”部分中打开CoffeeScript IDE,该部分显示在以下快照中。

编码地

Step 4

如果将CoffeeScript代码粘贴到main.coffee (可以更改文件名)并单击“ Preview按钮,则可以在控制台中看到已编译的JavaScript,如以下快照所示。

CoffeeScript IDE

CoffeeScript - Environment

最新版本的CoffeeScript的编译器是用CoffeeScript编写的。 要在没有浏览器的情况下在系统中运行CoffeeScript文件,您需要一个JavaScript运行时。

Node.js

Node.js是一个JavaScript框架,用于开发网络服务器应用程序。 它还充当JavaScript和操作系统之间的桥梁。

CoffeeScript的命令行版本作为Node.js包分发。 因此,要在系统中安装CoffeeScript(命令行),首先需要安装node.js.

Installing Node.js

以下是在系统中下载和安装Node.js的步骤。

Step 1

访问nodejs主页并通过单击下面给出的快照中的高亮按钮下载其稳定版本的Windows。

主页

Step 2

单击时,名为node-v5.50-x64.msc文件将下载到您的系统中,运行下载的文件以启动Node.js设置。 以下是Node.js设置向导的Welcome页面的快照。

点击下一步

Step 3

单击Node.js设置向导的“欢迎”页面中的“下一步”按钮,该向导将引导您进入“最终用户许可协议”页面。 接受许可协议,然后单击Next按钮,如下所示。

许可协议

Step 4

在下一页上,您需要将目标文件夹设置为要安装Node.js的路径。 将路径更改为所需的文件夹,然后单击“下一步”按钮。

设置目标文件夹

Step 5

在“ Custom setup页面中,选择Node.js运行时以安装node.exe文件,然后单击“下一步”。

自定义设置

Step 6

最后,单击Install按钮,它将启动Node.js安装。

单击安装

单击Node.js设置向导的Finish按钮,如下所示,以完成Node.js安装。

单击完成

安装CoffeeScript

Node.js为您提供命令提示符( Node.js command prompt )。 您可以通过在其中输入以下命令来全局安装CoffeeScript。

c:\> npm install -g coffeescript

执行上述命令时,将通过生成以下输出在您的系统中安装CoffeeScript。

安装CoffeeScript

验证 (Verification)

您可以通过键入以下命令来验证CoffeeScript的安装。

c:\> coffee -v

成功安装后,此命令将为您提供CoffeeScript的版本,如下所示。

验证

CoffeeScript - Command-line utility

在Node.js上安装CoffeeScript时,我们可以访问coffee-command line utility 。 在这里, coffee命令是关键命令。 使用此命令的各种选项,我们可以编译和执行CoffeeScript文件。

您可以使用-h--help选项查看coffee命令的选项列表。 打开Node.js command prompt并在其中执行以下命令。

c:\>coffee -help

此命令为您提供coffee的各种选项列表,以及每种coffee的操作说明,如下所示。

coffeecommand帮助

编译CoffeeScript代码

CoffeeScript文件以.coffee扩展名.coffee 。 您可以使用coffee命令的-c or --compile选项编译这些文件,如下所示。

c:\>coffee -c filename.coffee

例子 (Example)

假设系统中有一个文件,其中包含以下CoffeeScript代码,该代码在控制台上输出消息。

name = "Raju"
console.log "Hello"+name+" Welcome to IoWiki"

Note - console.log()函数在控制台上打印给定的字符串。

要编译上面的代码,请将其保存在名为sample.coffee的文件中。 打开Node.js命令提示符。 浏览保存文件的路径,并使用coffee command-line utilitycoffee command-line utility-c选项进行编译,如下所示。

c:\> coffee -c sample.coffee

在执行上述命令时,CoffeeScript编译器编译给定文件(sample.coffee)并将其保存在名为sample.js的当前位置,如下所示。

JS档案

如果打开sample.js文件,则可以观察生成的JavaScript,如下所示。

// Generated by CoffeeScript 1.10.0
(function() {
  var name;
  name = "Raju";
  console.log("Hello " + name + " Welcome to IoWiki");
}).call(this);

执行CoffeeScript代码

只需将文件名传递给Node.js命令提示符中的coffee命令,即可执行CoffeeScript文件,如下所示。

c:\> coffee sample.coffee

例子 (Example)

例如,让我们执行sample.coffee文件。 为此,请打开Node.js命令提示符。 浏览保存文件的路径并通过直接将其名称传递给coffee命令来执行该文件,如下所示。

执行

观看和编译

在某些情况下,我们可能会对脚本进行大量更改。 使用coffee命令的–w选项,可以查看脚本以进行更改。

您可以使用-wc选项同时查看和编译文件,如下所示。 当我们使用此选项时,每次在脚本中进行更改时都会重新编译该文件。

c:\>coffee -wc file_name

例子 (Example)

假设我们使用-wc选项编译了一个名为sample.coffee的文件,我们将脚本修改了三次。 每次我们更改脚本时, .coffee重新编译.coffee文件,并保留Node.js命令提示符,如下所示。

观察并编译

设置输出目录

使用-o选项,我们可以设置输出目录以放置已编译的JavaScript文件,如下所示。

c:\>coffee -o "Required path where we want our .js files" file_name

例子 (Example)

让我们通过在命令提示符中执行以下命令,使用-o选项将sample.coffee文件的JavaScript代码保存在E驱动器中名为data的文件夹中。

c:\>coffee -o E://data sample.coffee

以下是执行上述命令后给定文件夹的快照。 在这里,您可以观察sample.coffee的JavaScript文件

输出目录

打印编译的JavaScript

如果我们想在控制台上打印已编译的javascript,我们必须使用coffee命令的-p选项,如下所示。

c:\>coffee -p file_name

例子 (Example)

例如,您可以使用-p选项在控制台上打印sample.coffee文件的已编译JavaScript代码,如下所示。

打印JavaScript

REPL(读取评估打印循环)

CoffeeScript为您提供了一个REPL交互式shell。 此shell用于评估CoffeeScript表达式。 您可以在此shell中键入任何CoffeeScript代码并立即获得结果。 您可以通过执行coffee命令打开REPL而不使用任何选项,如下所示。

执行Coffee命令

使用此shell,我们可以为变量赋值,创建函数和评估结果。 如下面的屏幕截图所示,如果我们在REPL中调用函数,它会打印函数的值。 如果我们给它一个表达式,它会计算并打印表达式的结果。 如果我们只是在其中键入语句,它将打印最后一个语句的值。

REPL用法

在REPL中,您可以通过按ctrl+v访问多行模式,您可以使用多行(如函数)评估代码,然后再次按ctrl+v可以从中恢复到REPL模式。 以下是多线模式的示例用法。

REPL Mutiline功能

通过浏览器运行CoffeeScript

我们可以像使用JavaScript的

<script src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"
   type="text/javascript" charset="utf-8"></script>
<script type="text/coffeescript">
  # Some CoffeeScript
</script>

但为此,我们必须在每个应用程序中导入库,并在显示输出之前逐行解释CoffeeScript代码。 这会降低您的应用程序速度,因此不建议采用这种方法。

因此,要在应用程序中使用CoffeeScript,您需要使用Coffee命令行实用程序预编译它们,然后您可以在应用程序中使用生成的JavaScript。

CoffeeScript - Syntax

在上一章中,我们已经了解了如何安装CoffeeScript。 在本章中,让我们看看CoffeeScript的语法。

与JavaScript的语法相比,CoffeeScript的语法更加优雅。 它避免了花括号,分号和可变减速等麻烦的功能。

CoffeeScript语句

与许多其他编程语言(如C,C ++和Java)不同,CoffeeScript中的语句不以分号(;)结尾。 而不是那样,每个新行都被CoffeeScript编译器视为一个单独的语句。

例子 (Example)

以下是CoffeeScript语句的示例。

name = "Javed"
age = 26

以同样的方式,我们可以通过使用分号分隔它们来在一行中编写两个语句,如下所示。

name = "Javed";age = 26

CoffeeScript变量(无变量关键字)

在JavaScript中,我们在创建变量之前使用var关键字声明变量,如下所示。

var name = "Javed"
var age = 20

在CoffeeScript中创建变量时,无需使用var关键字声明它们。 我们可以直接创建一个变量,只需为它赋值,如下所示。

name = "Javed"
age = 20

没有圆括号

通常,我们在声明函数,调用函数时使用括号,并且还要分隔代码块以避免歧义。 在CoffeeScript中,不需要使用括号,在创建函数时,我们使用箭头标记( -》 )而不是括号,如下所示。

myfunction = -> alert "Hello"

不过,我们必须在某些情况下使用括号。 在调用不带参数的函数时,我们将使用括号。 例如,如果我们在CoffeeScript中有一个名为my_function的函数,那么我们必须调用它,如下所示。

my_function()

同样,我们也可以使用括号分隔模糊代码。 如果你观察下面的例子,没有大括号,结果是2233,使用大括号,它将是45。

alert "The result is  "+(22+33)

没有卷曲的大括号

在JavaScript中,对于诸如函数,循环和条件语句之类的块代码,我们使用花括号。 在CoffeeScript中,不需要使用花括号。 相反,我们必须在体内保持适当的缩进(白色空间)。 这是受Python语言启发的功能。

以下是CoffeeScript中的一个函数示例。 在这里你可以观察到,我们使用三个空格作为缩进而不是花括号来分隔函数的主体。

myfunction = -> 
   name = "John"
   alert "Hello"+name

CoffeeScript评论

在任何编程语言中,我们使用注释来编写有关我们编写的代码的描述。 这些评论不被视为计划的一部分。 CoffeeScript中的注释类似于Ruby语言的注释。 CoffeeScript提供两种类型的注释,如下所示 -

Single-line Comments

每当我们想在CoffeeScript中注释一行时,我们只需要在它之前放置一个哈希标记,如下所示。

# This is the single line comment in CoffeeScript

跟随散列标记( # )的每一行都被CoffeeScript编译器视为注释,它编译除了注释之外的给定文件中的其余代码。

多行评论

每当我们想要在CoffeeScript(多行)中注释多行时,我们可以通过将这些行包装在一对三重哈希标记中来实现,如下所示。

###
These are the multi line comments in CoffeeScript
We can write as many number of lines as we want 
within the pair of triple hash tags.
###

CoffeeScript保留关键字

CoffeeScript中所有保留字的列表如下表所示。 它们不能用作CoffeeScript变量,函数,方法,循环标签或任何对象名称。

case

default

function

var

void

with

const

let

enum

export

import

native

__hasProp

__extends

__slice

__bind

__indexOf

implements

else

interface

package

private

protected

public

static

yield

true

false

null

this

new

delete

typeof

in

arguments

eval

instanceof

return

throw

break

continue

debugger

if

else

switch

for

while

do

try

catch

finally

class

extends

super

undefined

then

unless

until

loop

of

by

when

and

or

is

isnt

not

yes

no

on

off

CoffeeScript - Data Types

CoffeeScript数据类型

编程语言最基本的特征之一是它支持的数据类型集。 这些是可以用编程语言表示和操作的值的类型。

当CoffeeScript逐行编译为JavaScript时,CoffeeScript提供的数据类型与JavaScript相同。 除了CoffeeScript添加一些额外的本质这一事实。

CoffeeScript提供以下数据类型 -

  • Strings - 字符串数据类型通常表示一组字符,我们使用中间双引号(“”)表示字符串值。

    Example :“Raj”,“Rahman”

  • Number - 数字数据类型表示数值。

    Example :12,212等

  • Boolean - 布尔数据类型表示一位信息。 只有两个可能的值:true和false。

  • Arrays - Array对象允许您在单个变量中存储多个值。 它存储固定大小的相同类型元素的顺序集合。

    Example :student = [“Rahman”,“Ramu”,“Ravi”,“Robert”]

  • Objects - CoffeeScript中的对象与JavaScript中的对象类似,它们是属性的集合。 其中属性包含键和由分号(:)分隔的值。 简而言之,CoffeeScript对象是键值对的集合。

    Example :student = {name:“Mohammed”,年龄:24,电话:9848022338}

  • Null - 已定义且未包含任何值的变量被视为null。 这类似于JavaScript中的null值。

  • Undefined - 未分配任何值的变量被视为未定义变量。 如果在代码中使用此类变量,则会出现未定义的错误。

我们将在单独的章节中详细介绍数据类型Arrays和Objects。

CoffeeScript - Variables

变量只不过是命名容器。 您可以将数据放入这些容器中,然后使用其容器名称引用数据。

CoffeeScript变量

在JavaScript中,在使用变量之前,我们需要声明并初始化它(赋值)。 与JavaScript不同,在CoffeeScript中创建变量时,不需要使用var关键字声明它。 我们只是通过为文字赋值来创建一个变量,如下所示。

name = variable name

例子 (Example)

在下面的CoffeeScript代码中,我们分别定义了两个变量nameage ,string和number数据类型。 将其保存在名为variable_example.coffee的文件中。

name = "Javed"
age = 25

Compiling the code

通过在命令提示符中执行以下命令来编译上述CoffeeScript代码。

c:\> compile -c variable_example.coffee

在编译时,将生成一个名为variable_example.js的JavaScript文件,其中包含以下内容。 在这里,您可以观察到编译器代表我们使用var关键字声明了变量(年龄和名称)。

// Generated by CoffeeScript 1.10.0
(function() {
  <b class="notranslate">var age, name;</b>
  name = "Javed";
  age = 25;
}).call(this);

可变范围

变量的范围是程序中定义它的区域。 JavaScript和CoffeeScript变量只有两个范围。

  • Global Variables - 全局变量具有全局范围,这意味着它可以在JavaScript代码中的任何位置使用。

  • Local Variables - 局部变量仅在定义它的函数中可见。 函数参数始终是该函数的本地参数。

JavaScript中的变量问题

在JavaScript中,每当我们在不使用var关键字的情况下定义变量时,都会使用全局范围创建变量。 这会导致很多问题。 考虑以下示例 -

<script type = "text/javascript">
   var i = 10;
   document.write("The value of global variable i is "+ i);   
   document.write("<br>");
   test();
   function test() {
      i = 20;
      document.write("The value of local variable i is "+i);
      document.write("<br>");
   }
   document.write("The value of global variable i is "+i);
</script>

执行时,上面的JavaScript为您提供以下输出 -

The value of global variable i is 10
The value of local variable i is 20
The value of global variable i is 20

在上面的例子中,我们在全局空间中创建了一个名为i的变量,并为其赋值10。 在函数中,在尝试创建具有相同名称的局部变量时,我们声明为i=20 ; 没有var关键字。 由于我们错过了var关键字,因此全局变量i的值被重新赋值为20。

因此,建议使用var关键字声明变量。

CoffeeScript中的变量范围

每当我们编译CoffeeScript文件时,CoffeeScript编译器都会创建一个匿名函数,并且在该函数中,它会逐行将CoffeeScript代码反编译为JavaScript。 (如果需要,我们可以使用compile命令的-b--bare选项删除顶级函数包装器)我们创建的每个变量都是使用匿名函数中的var关键字声明的,因此,默认情况下,每个变量都是如此在CoffeeScript中是本地的。

(function() {
  <b class="notranslate">var age, name;</b>
  name = "javed";
  age = 20;
}).call(this);

无论如何,如果我们想要,我们可以用全局命名空间声明一个变量。 我们可以明确地做到,如下所示。

obj = this
obj.age = 30

CoffeeScript Variable Names (Literals)

在CoffeeScript中命名变量时,请记住以下规则。

  • 您不应将任何CoffeeScript保留关键字用作变量名称。 这些关键字将在下一节中提到。 例如,break或Boolean变量名称无效。

  • CoffeeScript变量名称不应以数字(0-9)开头。 它们必须以字母或下划线字符开头。 例如,123test是无效的变量名称,但_123test是有效的。

  • CoffeeScript变量名称区分大小写。 例如, Namename是两个不同的变量。

CoffeeScript - Operators and Aliases

CoffeeScript运算符

运算符是告诉编译器执行特定数学或逻辑函数的符号。 让我们采用一个简单的表达式4 + 5 is equal to 9 。 这里4和5被称为operands ,'+'被称为operator

除了一些差异之外,CoffeeScript提供的运算符与JavaScript中的运算符相同。 JavaScript中有一些有问题的运算符。 CoffeeScript要么删除它们要么修改它们的功能,它还引入了一些新的操作符。

以下是CoffeeScript支持的运算符列表。

  • 算术运算符
  • 比较运算符
  • 逻辑(或关系)运算符
  • 分配运算符

CoffeeScript别名

除了运算符,CoffeeScript还提供别名。 CoffeeScript为各种运算符和符号提供别名,以使您的CoffeeScript代码可读且更加用户友好。

让我们一个一个地看看CoffeeScript的所有运算符和别名。

算术运算符 (Arithmetic Operators)

CoffeeScript支持以下算术运算符。 假设变量A保持10 ,变量B保持20 ,则 -

显示示例

S.No 运算符和描述
1

+ (Addition)

添加两个操作数

A + B = 30
2

− (Subtraction)

从第一个中减去第二个操作数

A - B = -10
3

* (Multiplication)

将两个操作数相乘

A * B = 200
4

/ (Division)

用分母除以分子

B/A = 2
5

% (Modulus)

输出整数除法的余数

B%A = 0
6

++ (Increment)

将整数值增加1

A ++ = 11
7

-- (Decrement)

将整数值减1

A-- = 9

比较运算符 (Comparison Operators)

JavaScript支持以下比较运算符。 假设变量A保持10 ,变量B保持20 ,则 -

显示示例

S.No 运算符和描述
1

= = (Equal)

检查两个操作数的值是否相等,如果是,则条件成立。

(A == B)不是真的。
2

!= (Not Equal)

检查两个操作数的值是否相等,如果值不相等,则条件变为true。

(A!= B)是真的。
3

》 (Greater than)

检查左操作数的值是否大于右操作数的值,如果是,则条件变为真。

(A> B)不是真的。
4

《 (Less than)

检查左操作数的值是否小于右操作数的值,如果是,则条件变为真。

(A < B) 为真
5

》= (Greater than or Equal to)

检查左操作数的值是否大于或等于右操作数的值,如果是,则条件变为真。

(A> = B)不是真的。
6

《= (Less than or Equal to)

检查左操作数的值是否小于或等于右操作数的值,如果是,则条件变为真。

(A <= B)是真的。

下表显示了少数比较运算符的别名。 假设A持有20而变量B持有20

显示示例

操作者 别号
= =(等于) is A is B给你真实的。
!= =(不等于) isnt A isnt B给你假。

逻辑运算符 (Logical Operators)

CoffeeScript支持以下逻辑运算符。 假设变量A保持10 ,变量B保持20 ,则 -

显示示例

S.No 运算符和描述
1

&& (Logical AND)

如果两个操作数都不为零,则条件成立。

(A && B)是真的。
2

|| (Logical OR)

如果两个操作数中的任何一个非零,则条件变为真。

(A || B)是真的。
3

! (Logical NOT)

反转其操作数的逻辑状态。 如果条件为真,则Logical NOT运算符将使其为false。

! (A && B)是假的。

下表显示了某些逻辑运算符的别名。 假设X保持为true ,变量Y保持为false

显示示例

操作者 别号
&& (Logical AND) and X and Y给你假
|| (逻辑或) or X or Y给你真实
! (不是x) not not X给你假

按位运算符 (Bitwise Operators)

CoffeeScript支持以下按位运算符。 假设变量A保持2而变量B保持3 ,则 -

显示示例

S.No 运算符和描述
1

& (Bitwise AND)

它对其整数参数的每个位执行布尔AND运算。

(A&B)是2。
2

| (BitWise OR)

它对其整数参数的每个位执行布尔OR运算。

(A | B)是3。
3

^ (Bitwise XOR)

它对其整数参数的每个位执行布尔异或运算。 异或表示操作数1为真或操作数2为真,但不是两者。

(A ^ B)是1。
4

~ (Bitwise Not)

它是一元运算符,通过反转操作数中的所有位来操作。

(~B) is -4.
5

《《 (Left Shift)

它将第一个操作数中的所有位向左移动第二个操作数中指定的位数。 新位用零填充。 将一个值左移一个位置相当于将其乘以2,移位两个位置相当于乘以4,依此类推。

(A << 1)是4。
6

》》 (Right Shift)

二进制右移运算符。 左操作数的值向右移动右操作数指定的位数。

(A >> 1)是1。

赋值操作符 (Assignment Operators)

CoffeeScript支持以下赋值运算符 -

显示示例

S.No 运算符和描述
1

= (Simple Assignment )

将值从右侧操作数分配给左侧操作数

C = A + B将A + B的值分配给C
2

+= (Add and Assignment)

它将右操作数添加到左操作数并将结果赋给左操作数。

C + = A等于C = C + A.
3

-= (Subtract and Assignment)

它从左操作数中减去右操作数,并将结果赋给左操作数。

C - = A相当于C = C - A.
4

*= (Multiply and Assignment)

它将右操作数与左操作数相乘,并将结果赋给左操作数。

C * = A等于C = C * A.
5

/= (Divide and Assignment)

它将左操作数与右操作数分开,并将结果赋给左操作数。

C/= A相当于C = C/A.
6

%= (Modules and Assignment)

它使用两个操作数来获取模数,并将结果赋给左操作数。

C%= A等于C = C%A

Note - 相同的逻辑适用于按位运算符,因此它们将变为“”=,“”=,“”=,&=,| =和^ =。

CoffeeScript中的等式运算符

使用JavaScript时,您将遇到两种类型的相等运算符=====

JavaScript中的==运算符是type coercive ,即,如果操作中两个操作数的类型不同,则将其中一个运算符的数据类型转换为其他运算符,然后比较两者。

CoffeeScript避免了这种不受欢迎的强制,它将==运算符编译为JavaScript ===的严格比较运算符。

如果我们使用===比较两个操作数,那么它返回true ,只有当它们的值和数据类型都相等时,否则返回false

例子 (Example)

请考虑以下示例。 这里我们有两个变量aba保存整数类型的值21, b保持相同的值,但它是string类型。 在CoffeeScript中,当我们比较ab ,结果将为false 。 (因为CoffeeScript的==运算符转换为JavaScript的===运算符)

a=21
b="21"
result = 21=='21'
console.log result

在编译时,上面的CoffeeScript生成以下JavaScript

// Generated by CoffeeScript 1.10.0
(function() {
  var a, b, result;
  a = 21;
  b = "21";
  <b class="notranslate">result = a === b;</b>
  console.log(result);
}).call(this);

执行时,它会产生以下输出。

false

存在主义运算符

CoffeeScript提供了一个新的运算符,称为存在运算符,用于验证变量的存在。 它用?表示? 。 除非变量为null或未定义,否则存在运算符返回true。

例子 (Example)

下面给出了存在运算符的一个例子。 这里我们有三个变量,即name, agesubject ,我们正在使用存在运算符验证变量名称和电话的存在。

name="Ramu"
age=24
subject="Engineering"
verify_name = <b class="notranslate">name?</b>
verify_phone = <b class="notranslate">phone?</b>
console.log verify_name
console.log verify_phone

在编译时,这将生成以下JavaScript代码。

// Generated by CoffeeScript 1.10.0
(function() {
  var age, name, subject, verify_name, verify_phone;
  name = "Ramu";
  age = 24;
  subject = "Engineering";
  verify_name = name != null;
  verify_phone = typeof phone !== "undefined" && phone !== null;
  console.log(verify_name);
  console.log(verify_phone);
}).call(this);

如果我们执行上面的CoffeeScript文件,它会产生以下输出。

true
false

Note - 我们有存在运算符的存取变体? 。 我们可以用它代替。 运算符以找出空引用。

链式比较

与在Python中一样,我们可以在CoffeeScript中的单个表达式中使用一系列比较运算符。

例子 (Example)

以下是使用链式比较的示例。

score = 70
passed = 100 > score > 40
console.log passed

在编译时,示例CoffeeScript为您提供以下JavaScript代码。

// Generated by CoffeeScript 1.10.0
(function() {
  var passed, score;
  score = 70;
  passed = (100 > score && score > 40);
  console.log(passed);
}).call(this);

如果执行上述CoffeeScript代码,则会生成以下输出。

true

Note - CoffeeScript删除了三元运算符; 而不是它,我们可以使用inline if语句。

CoffeeScript别名

通常,CoffeeScript为各种运算符和符号提供别名,以使您的CoffeeScript代码可读且更加用户友好。 以下是CoffeeScript提供的别名。

名称 运算符/符号 别名
"equals to" operator==is
"not equals to" operator!==isnt
"not" operator!not
"and" operator&&and
"or" operator||or
boolean value truetruetrue, yes, on
boolean value falsefalseoff, no
当前对象 this@
新行(或)半冒号 \n或; then
Inverse of if ! 如果 unless
测试阵列存在 in
测试对象存在 of
Exponentiation a ** b
整数除法 a // b
dividend dependent modulo a %% b

例子 (Example)

以下示例显示如何在CoffeeScript中使用别名 -

a=21; b=21
x = true; y = false
console.log a is b
console.log a isnt b
console.log x and y
console.log x or y
console.log yes or no
console.log on or off
console.log a**b
console.log a//b
console.log a%%b

在编译上面的示例时,它为您提供以下JavaScript代码。

// Generated by CoffeeScript 1.10.0
(function() {
  var a, b, x, y,
    modulo = function(a, b) { return (+a % (b = +b) + b) % b; };
  a = 21;
  b = 21;
  x = true;
  y = false;
  console.log(a === b);
  console.log(a !== b);
  console.log(x && y);
  console.log(x || y);
  console.log(true || false);
  console.log(true || false);
  console.log(Math.pow(a, b));
  console.log(Math.floor(a/b));
  console.log(modulo(a, b));
}).call(this);

如果您执行上面的CoffeeScript文件,它会产生以下输出 -

true
false
false
true
true
true
5.842587018385982e+27
1
0

CoffeeScript - Conditionals

在编程时,我们遇到一些场景,我们必须从给定的路径集中选择路径。 在这种情况下,我们需要条件语句。 条件语句有助于我们做出决策并执行正确的操作。

以下是大多数编程语言中的典型决策结构的一般形式。

决策结构

JavaScript支持if语句(包括其变体)和switch语句。 除了JavaScript中提供的条件之外,CoffeeScript还包括unless声明,否定if,甚至更多。

以下是CoffeeScript提供的条件语句。

S.No. 声明和说明
1 if 语句

if语句由一个布尔表达式后跟一个或多个语句组成。 当给定的布尔表达式为true时,将执行这些语句。

2 if...else 语句

if语句后面可以跟一个可选的else语句,该语句在布尔表达式为false时执行。

3 unless statement

unless语句类似于使用布尔表达式后跟一个或多个语句的if语句。 当给定的布尔表达式为false时,将执行这些语句。

4 unless...else statement

unless语句后面跟一个可选的else语句,该语句在布尔表达式为真时执行。

5 switch 语句

switch语句允许测试变量与值列表的相等性。

CoffeeScript中的关键字

ifunless语句是以多行写入的块语句。 CoffeeScript提供了then关键字,我们可以在一行中编写ifunless语句。

以下是CoffeeScript中使用then关键字编写的语句。

S.No. 声明和说明
1 if-then statement

使用if-then语句,我们可以在一行中编写CoffeeScript的if语句。 它由一个布尔表达式后跟then关键字组成,后跟一个或多个语句。 当给定的布尔表达式为true时,将执行这些语句。

2 if-then...else statement

if-then语句后跟一个可选的else语句,该语句在布尔表达式为false时执行。 使用if-then ... else语句,我们可以在一行中编写if ... else语句。

3 unless-then statement

使用unless-then语句,我们可以在一行中编写CoffeeScript的unless语句。 它由一个布尔表达式后跟then关键字组成,后跟一个或多个语句。 当给定的布尔表达式为false时,将执行这些语句。

4 unless...then else statement

除非后面的语句后面跟一个可选的else语句,该语句在布尔表达式为true时执行。 使用unless-then ... else语句,我们可以在一行中编写除非... else语句。

postfix if和postfix除非语句

在CoffeeScript中,您还可以编写具有代码块的ifunless语句,然后是ifunless关键字,如下所示。 这是这些语句的后缀形式。 在CoffeeScript中编写程序时很方便。

#Postfix if
Statements to be executed <b class="notranslate">if expression</b>
#Postfix unless
Statements to be executed <b class="notranslate">unless expression</b>

显示例子

CoffeeScript - Loops

编码时,您可能会遇到需要反复执行代码块的情况。 在这种情况下,您可以使用循环语句。

通常,语句按顺序执行:首先执行函数中的第一个语句,然后执行第二个语句,依此类推。

循环语句允许我们多次执行语句或语句组。 下面给出的是大多数编程语言中循环语句的一般形式

循环架构

JavaScript提供while, forfor..in循环。 CoffeeScript中的循环与JavaScript中的循环类似。

while循环及其变体是CoffeeScript中唯一的循环结构。 CoffeeScript不是常用的for循环,而是为您提供在后面的章节中详细讨论的Comprehensions

CoffeeScript中的while循环

while循环是CoffeeScript提供的唯一低级循环。 它包含一个布尔表达式和一个语句块。 只要给定的布尔表达式为真, while循环就会重复执行指定的语句块。 表达式变为false后,循环终止。

语法 (Syntax)

以下是CoffeeScript中while循环的语法。 这里,没有必要使用括号来指定布尔表达式,我们必须使用(一致数量的)空格缩进循环体,而不是用花括号包装它。

while <b class="notranslate">expression</b>
   statements to be executed

例子 (Example)

以下示例演示了CoffeeScript中while循环的用法。 将此代码保存在名为while_loop_example.coffee的文件中

console.log "Starting Loop "
count = 0  
while count < 10
   console.log "Current Count : " + count
   count++;
console.log "Set the variable to different value and then try"

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c while_loop_example.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var count;
  console.log("Starting Loop ");
  count = 0;
  while (count < 10) {
    console.log("Current Count : " + count);
    count++;
  }
  console.log("Set the variable to different value and then try");
}).call(this); 

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

c:\> coffee while_loop_example.coffee

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

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Set the variable to different value and then try 

变异的同时

CoffeeScript中的While循环有两个变体,即until variantloop variant

S.No. 循环类型和描述
1 直到变种的同时

while循环的until变量包含一个布尔表达式和一个代码块。 只要给定的布尔表达式为false,就执行此循环的代码块。

2 while循环变体

loop变量等同于具有真值的while循环(while true) 。 这个循环中的语句将重复执行,直到我们使用Break语句退出循环。

CoffeeScript - Comprehensions

在上一章中,我们学习了CoffeeScript提供的各种循环,以及它的变体。 除此之外,CoffeeScript还提供了额外的循环结构,称为comprehensions

如果我们明确地添加可选的guard子句和当前数组索引的值,这些理解将替换其他编程语言中的for循环。 使用理解,我们可以迭代数组和对象,迭代数组的表达式是表达式,我们可以在函数中返回它们或分配给变量。

S.No. 声明和说明
1 因为...理解

for..in理解是CoffeeScript中理解的基本形式,使用它我们可以迭代列表或数组的元素。

2 为了理解

就像Arrays CoffeeScriptScript提供了一个容器来存储称为对象的键值对。 我们可以使用CoffeeScript提供的for..of理解来迭代对象。

3 list comprehensions

CoffeeScript中的list推导用于将对象数组映射到另一个数组。

理解指数

列表/元素数组具有可用于理解的索引。 您可以使用变量在结合中使用它,如下所示。

for student,i in [element1, element2, element3]

例子 (Example)

以下示例演示了CoffeeScript中for…in的索引的用法。 将此代码保存在名为for_in_index.coffee的文件中

for student,i in ['Ram', 'Mohammed', 'John']
   console.log "The name of the student with id "+i+" is: "+student 

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c for_in_index.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var i, j, len, ref, student;
  ref = ['Ram', 'Mohammed', 'John'];
  for (i = j = 0, len = ref.length; j < len; i = ++j) {
    student = ref[i];
    console.log("The name of the student with id " + i + " is: " + student);
  }
}).call(this);

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

c:\> coffee for_in_index.coffee

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

The name of the student with id 0 is: Ram
The name of the student with id 1 is: Mohammed
The name of the student with id 2 is: John 

Postfix形式的理解

就像postfix ifunless ,CoffeeScript提供了Comprehensions的后缀形式,它在编写代码时很方便。 使用这个,我们可以在一行中编写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}
显示例子

分配给变量

我们用于迭代数组的理解可以分配给变量,也可以由函数返回。

例子 (Example)

考虑下面给出的例子。 在这里,您可以观察到我们使用for..in理解检索了数组的元素,并将其分配给名为names的变量。 我们还有一个函数,它使用return关键字显式返回一个理解。 将此代码保存在名为example.coffee的文件中

my_function =->
   student = ['Ram', 'Mohammed', 'John']
   #Assigning comprehension to a variable
   names = (x for x in student )
   console.log "The contents of the variable <b class="notranslate">names</b> are ::"+names
   #Returning the comprehension
   return x for x in student
console.log "The value returned by the function is "+my_function() 

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c example.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var my_function;
  my_function = function() {
    var i, len, names, student, x;
    student = ['Ram', 'Mohammed', 'John'];
    names = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = student.length; i < len; i++) {
        x = student[i];
        results.push(x);
      }
      return results;
    })();
    console.log("The contents of the variable names are ::" + names);
    for (i = 0, len = student.length; i < len; i++) {
      x = student[i];
      return x;
    }
  };
  console.log("The value returned by the function is " + my_function());
}).call(this);

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

c:\> coffee example.coffee

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

The contents of the variable names are ::Ram,Mohammed,John
The value returned by the function is Ram 

by关键字

CoffeeScript提供范围来定义元素列表。 例如,范围[1..10]相当于[1,2,3,4,5,6,7,8,9,10],其中每个元素都递增1.我们也可以改变这个增量使用理解by关键字。

例子 (Example)

以下示例演示了CoffeeScript提供的for..in理解的by关键字的用法。 将此代码保存在名为by_keyword_example.coffee的文件中

array = (num for num in [1..10] by 2)
console.log array

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c by_keyword_example.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var array, num;
  array = (function() {
    var i, results;
    results = [];
    for (num = i = 1; i <= 10; num = i += 2) {
      results.push(num);
    }
    return results;
  })();
  console.log(array);
}).call(this);

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

c:\> coffee by_keyword_example.coffee

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

[ 1, 3, 5, 7, 9 ] 

CoffeeScript - 函数

函数是一个可重用代码块,可以在程序中的任何位置调用。 这消除了一次又一次地编写相同代码的需要。 它可以帮助程序员编写模块化代码。

函数允许程序员将大程序划分为许多小而易于管理的函数。

通常,使用JavaScript,我们可以定义两种类型的函数 - named functions ,带函数名称的常规函数​​和Function expressions 。 使用函数表达式,我们可以为变量赋值。

//named function
function sayHello(){
   return("Hello there");
}
//function expressions
var message = function sayHello(){
   return("Hello there");
}

CoffeeScript中的函数

与JavaScript相比,CoffeeScript中的函数语法更简单。 在CoffeeScript中,我们只定义函数表达式。

CoffeeScript中删除了function关键字。 要在此定义函数,我们必须使用细箭头( -》 )。

在幕后,CoffeeScript编译器将箭头转换为JavaScript中的函数定义,如下所示。

(function() {});

在CoffeeScript中使用return关键字不是强制性的。 CoffeeScript中的每个函数都会自动返回函数中的最后一个语句。

  • 如果我们想要返回到调用函数或在函数结束之前返回一个值,那么我们可以使用return关键字。

  • 除了内联函数(单行函数)之外,我们还可以在CoffeeScript中定义多行函数。 由于花括号被消除了,我们可以通过保持适当的缩进来实现。

定义一个函数 (Defining a Function)

以下是在CoffeeScript中定义函数的语法。

function_name = <b class="notranslate">-></b> function_body

例子 (Example)

下面给出了CoffeeScript中的一个函数示例。 在这里,我们创建了一个名为greet的函数。 此函数自动返回其中的语句。 将其保存在名为function_example.coffee的文件中

greet = -> "This is an example of a function"
<p></p>

通过在命令提示符中执行以下命令来编译它。

c:\>coffee -c function_example.coffee

在编译时,它会生成以下JavaScript代码。 在这里,您可以观察到CoffeeScript编译器自动在名为greet()的函数中返回字符串值。

// Generated by CoffeeScript 1.10.0
(function() {
  var greet;
  greet = function() {
    return "This is an example of a function";
  };
}).call(this);

Multi-line 函数

我们还可以通过维护缩进而不是花括号来定义具有多行的函数。 但是我们必须与我们在整个函数中遵循的缩进一致。

greet =  ->
  console.log "Hello how are you"

在编译时,上面的CoffeeScript为您提供以下JavaScript代码。 CoffeeScript编译器抓取我们使用缩进分隔并放在花括号内的函数体。

// Generated by CoffeeScript 1.10.0
(function() {
  var greet;
  greet = function() {
    return console.log("Hello how are you");
  };
}).call(this);

带参数的函数

我们还可以使用括号在函数中指定参数,如下所示。

add =(a,b) ->
  c=a+b
  console.log "Sum of the two numbers is: "+c

在编译上面的CoffeeScript文件时,它将生成以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var add;
  add = function(a, b) {
    var c;
    c = a + b;
    return console.log("Sum of the two numbers is: " + c);
  };
}).call(this);

调用函数

定义一个函数后,我们需要调用该函数。 您可以通过在其名称后面放置括号来简单地调用函数,如以下示例所示。

add = ->
  a=20;b=30
  c=a+b
  console.log "Sum of the two numbers is: "+c  
add()

在编译时,上面的示例为您提供以下JavaScript

// Generated by CoffeeScript 1.10.0
(function() {
  var add;
  add = function() {
    var a, b, c;
    a = 20;
    b = 30;
    c = a + b;
    return console.log("Sum of the two numbers is: " + c);
  };
  add();
}).call(this);

在执行上述CoffeeScript代码时,它会生成以下输出。

Sum of the two numbers is: 50

使用参数调用函数

以同样的方式,我们可以通过将函数传递给它来调用带有参数的函数,如下所示。

my_function argument_1,argument_2
or
my_function (argument_1,argument_2)

Note - 在通过向其传递参数来调用函数时,括号的用法是可选的。

在下面的示例中,我们创建了一个名为add()的函数,它接受两个参数,并且我们已经调用了它。

add =(a,b) ->
  c=a+b
  console.log "Sum of the two numbers is: "+c
add 10,20 

在编译时,上面的示例为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var add;
  add = function(a, b) {
    var c;
    c = a + b;
    return console.log("Sum of the two numbers is: " + c);
  };
  add(10, 20);
}).call(this);

在执行时,上面的CoffeeScript代码会生成以下输出。

Sum of the two numbers is: 30

默认参数

CoffeeScript也支持默认参数。 我们可以将默认值分配给函数的参数,如以下示例所示。

add =(a = 1, b = 2) ->
  c=a+b
  console.log "Sum of the two numbers is: "+c
add 10,20
#Calling the function with default arguments
add()

在编译时,上面的CoffeeScript生成以下JavaScript文件。

// Generated by CoffeeScript 1.10.0
(function() {
  var add;
  add = function(a, b) {
    var c;
    if (a == null) {
      a = 1;
    }
    if (b == null) {
      b = 2;
    }
    c = a + b;
    return console.log("Sum of the two numbers is: " + c);
  };
  add(10, 20);
  add()
}).call(this);

在执行上述CoffeeScript代码时,它会生成以下输出。

Sum of the two numbers is: 30
Sum of the two numbers is: 3

CoffeeScript - Strings

String对象允许您使用一系列字符。 与大多数编程语言一样,CoffeeScript中的字符串使用引号声明为 -

my_string = "Hello how are you"
console.log my_string

在编译时,它将生成以下JavaScript代码。

// Generated by CoffeeScript 1.10.0
(function() {
  var my_string;
  my_string = "Hello how are you";
  console.log(my_string);
}).call(this);

字符串连接 (String Concatenation)

我们可以使用“+”符号连接两个字符串,如下所示。

new_string = "Hello how are you "+"Welcome to IoWiki"
console.log new_String

在编译时,它将生成以下JavaScript代码。

// Generated by CoffeeScript 1.10.0
(function() {
  var new_string;
  new_string = "Hello how are you " + "Welcome to IoWiki";
  console.log(new_String);
}).call(this);

如果执行上面的示例,则可以观察到连接的String,如下所示。

Hello how are you Welcome to IoWiki

字符串插值

CoffeeScript还提供了一个称为String interpolation的功能,用于在stings中包含变量。 CoffeeScript的这一功能灵感来自Ruby语言。

字符串插值使用双引号"" ,散列标记#和一对花括号{ } 。 String以双引号声明,并且要插入的变量包含在花括号中,花括号以哈希标记作为前缀,如下所示。

name = "Raju"
age = 26
message =<b class="notranslate">"Hello #{name} your age is #{age}"</b>
console.log message

在编译上面的示例时,它会生成以下JavaScript。 在这里,您可以观察到使用+符号将字符串插值转换为正常连接。

// Generated by CoffeeScript 1.10.0
(function() {
  var age, message, name;
  name = "Raju";
  age = 26;
  <b class="notranslate">message = "Hello " + name + " your age is " + age;</b>
  console.log(message);
}).call(this);

如果您执行上面的CoffeeScript代码,它会为您提供以下输出。

Hello Raju your age is 26

仅当字符串包含在双引号" "之间时,才会插入作为#{variable}传递的#{variable} 。 使用单引号' '而不是双引号会产生直线,而不是插值。 请考虑以下示例。

name = "Raju"
age = 26
message ='Hello #{name} your age is #{age}'
console.log message

如果我们在插值中使用单引号而不是双引号,您将获得以下输出。

Hello #{name} your age is #{age}

CoffeeScript允许字符串中的多行而不连接它们,如下所示。

my_string = "hello how are you
Welcome to iowiki
Have a nice day."
console.log my_string

它生成以下输出。

hello how are you Welcome to iowiki Have a nice day.

JavaScript字符串对象

JavaScript的String对象允许您使用一系列字符。 此对象为您提供了许多方法来对Stings执行各种操作。

由于我们可以在CoffeeScript代码中使用JavaScript库,因此我们可以在CoffeeScript程序中使用所有这些方法。

字符串方法

以下是JavaScript的String对象的方法列表。 单击这些方法的名称以获取演示它们在CoffeeScript中的用法的示例。

S.No. 方法和描述
1 charAt()

返回指定索引处的字符。

2 charCodeAt()

返回一个数字,指示给定索引处字符的Unicode值。

3 concat()

合并两个字符串的文本并返回一个新字符串。

4 indexOf()

返回第一次出现的指定值的调用String对象中的索引,如果未找到,则返回-1。

5 lastIndexOf()

返回最后一次出现的指定值的调用String对象中的索引,如果未找到,则返回-1。

6 localeCompare()

返回一个数字,指示引用字符串是在排序顺序之前还是之后出现,或者与排序顺序中的给定字符串相同。

7 match()

用于将正则表达式与字符串匹配。

8 search()

执行搜索正则表达式与指定字符串之间的匹配项。

9 slice()

提取字符串的一部分并返回一个新字符串。

10 split()

通过将字符串分隔为子字符串将String对象拆分为字符串数组。

11 substr()

返回从指定位置开始通过指定字符数的字符串中的字符。

12 toLocaleLowerCase()

在尊重当前区域设置的同时,字符串中的字符将转换为小写字母。

13 toLocaleUpperCase()

在尊重当前语言环境的同时,字符串中的字符将转换为大写字母。

14 toLowerCase()

返回转换为小写的调用字符串值。

15 toUpperCase()

返回转换为大写的调用字符串值。

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>

CoffeeScript - Objects

CoffeeScript中的对象与JavaScript中的对象类似。 这些是属性的集合,其中属性包括键和由分号(:)分隔的值。 简而言之,CoffeeScript对象是键值对的集合。 使用花括号定义对象,将空对象表示为{}

语法 (Syntax)

下面给出了CoffeeScript中对象的语法。 在这里,我们将对象的键值对放在花括号中,并使用逗号( , )分隔它们。

object ={key1: value, key2: value,......keyN: value}

例子 (Example)

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

student = {name: "Mohammed", age: 24, phone: 9848022338 } 

打开command prompt并编译.coffee文件,如下所示。

> coffee -c objects_example.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var student;
  student = {
    name: "Mohammed",
    age: 24,
    phone: 9848022338
  };
}).call(this);

就像在数组中一样,我们可以通过在新行中指定键值对来删除逗号,如下所示。

student = {
  name: "Mohammed" 
  age: 24
  phone: 9848022338 
  }

缩进而不是花括号

就像CoffeeScript中的其他块语句一样,我们可以使用缩进而不是花括号{} ,如以下示例所示。

例子 (Example)

我们可以在没有花括号的情况下重写上面的例子,如下所示。

student = 
  name: "Mohammed" 
  age: 24
  phone: 9848022338 

嵌套对象

在CoffeeScript中,我们可以在对象中编写对象。

例子 (Example)

以下示例演示CoffeeScript中的嵌套对象。 将此代码保存在名为nested_objects.coffee的文件中

contact =
  personal:
    email: "personal@gmail.com"
    phone:  9848022338
  professional:
    email: "professional@gmail.com"
    phone:  9848033228

打开command prompt并编译.coffee文件,如下所示。

> coffee -c nested_objects.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var contact;
  contact = {
    personal: {
      email: "personal@gmail.com",
      phone: 9848022338
    },
    professional: {
      email: "professional@gmail.com",
      phone: 9848033228
    }
  };
}).call(this);

对对象的理解

要迭代对象的内容,我们可以使用理解。 迭代对象的内容与迭代数组的内容相同。 在对象中,由于我们必须检索两个元素键和值,因此我们将使用两个变量。

例子 (Example)

以下是一个示例,说明如何使用理解来迭代对象的内容。 将此代码保存在名为object_comprehensions.coffee的文件中

student = 
  name: "Mohammed" 
  age: 24
  phone: 9848022338 
console.log key+"::"+value for key,value of student

打开command prompt并编译.coffee文件,如下所示。

> coffee -c object_comprehensions.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var key, student, value;
  student = {
    name: "Mohammed",
    age: 24,
    phone: 9848022338
  };
  for (key in student) {
    value = student[key];
    console.log(key(+"::" + value));
  }
}).call(this);

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

> coffee object_comprehensions.coffee

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

name::Mohammed
age::24
phone::9848022338 

对象数组

在CoffeeScript中,数组也可以包含对象,如下所示。

  a = [
     object1_key1: value
     object1_key2: value
     object1_key3: value
  ,
     object2_key1: value
     object2_key2: value
     object2_key3: value
]

以下示例显示如何定义对象数组。 我们可以通过使用逗号(,)分隔它们来列出我们想要在数组中的对象的键值对。

students =[  
    name: "Mohammed" 
    age: 24
    phone: 9848022338 
  ,  
    name: "Ram" 
    age: 25
    phone: 9800000000 
  ,  
    name: "Ram" 
    age: 25
    phone: 9800000000   
 ]  
console.log student for student in students

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c array_of_objects.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var i, len, student, students;
  students = [
    {
      name: "Mohammed",
      age: 24,
      phone: 9848022338
    }, {
      name: "Ram",
      age: 25,
      phone: 9800000000
    }, {
      name: "Ram",
      age: 25,
      phone: 9800000000
    }
  ];
  for (i = 0, len = students.length; i < len; i++) {
    student = students[i];
    console.log(student);
  }
}).call(this);

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

c:\> coffee array_of_objects.coffee

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

{ name: 'Mohammed', age: 24, phone: 9848022338 }
{ name: 'Ram', age: 25, phone: 9800000000 }
{ name: 'Ram', age: 25, phone: 9800000000 }

保留关键字

JavaScript不允许保留关键字作为对象的属性名称,如果我们想要使用它们,我们必须使用双引号" "来包装它们。

例子 (Example)

请考虑以下示例。 这里我们创建了一个名为class的属性,它是一个保留关键字。 将此代码保存在名为reserved_keywords.coffee的文件中

student ={ 
  name: "Mohammed" 
  age: 24
  phone: 9848022338
  class: "X"
  }
console.log key+"::"+value for key,value of student

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c reserved_keywords.coffee

在编译时,它为您提供以下JavaScript。 在这里,您可以观察到CoffeeScript编译器代表我们用双引号包装了关键字类。

// Generated by CoffeeScript 1.10.0
(function() {
  var key, student, value;
  student = {
    name: "Mohammed",
    age: 24,
    phone: 9848022338,
    <b class="notranslate">"class": "X"</b>
  };
  for (key in student) {
    value = student[key];
    console.log(key + "::" + value);
  }
}).call(this);

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

c:\> coffee array_of_objects.coffee

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

name::Mohammed
age::24
phone::9848022338
class::X 

CoffeeScript - Ranges

在上一章中,我们在CoffeeScript中看到了Arrays,在编程时我们将面临一些场景,我们必须在数组中存储一系列数值,如下所示。

numbers =[1,2,3,4,5,6,7,8,9,10]
<p></p>

CoffeeScript提供了一种表达包含一系列数值的数组的简短方法,称为ranges 。 CoffeeScript的这个功能灵感来自Ruby。

语法 (Syntax)

范围由两个数值创建,即范围中的第一个和最后一个位置,由......或......分隔。对于两个点(1..4),范围包括(1,2,3,4); 有三个点(1 ... 4),范围不包括结尾(1,2,3)。

下面给出了CoffeeScript中范围的语法。 我们将在方括号[ ]之间的范围内定义值,就像数组一样。 在范围中,在存储一系列数值时,我们可以只指定由两个点( .. )分隔的begin值和end值,而不是提供整个序列的值,如下所示。

range =[Begin..End]

例子 (Example)

以下是CoffeeScript中范围的示例。 将其保存在名为ranges_example.coffee的文件中。

numbers =[0..9]
console.log "The contents of the range are: "+ numbers 

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c ranges_example.coffee

在编译时,它为您提供以下JavaScript。 在这里,您可以观察到范围被转换为完整的CoffeeScript数组。

// Generated by CoffeeScript 1.10.0
(function() {
  var numbers;
  <b class="notranslate">numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];</b>
  console.log("The contents of the range are:: " + numbers);
}).call(this);

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

c:\> coffee ranges_example.coffee

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

The contents of the range are:: 0,1,2,3,4,5,6,7,8,9

排除最终价值

范围被编译成包含所有数字的完整数组。 如果我们想要排除end值,那么我们必须使用三个点( ... )分离范围的startend元素,如下所示。

range =[Begin...End]

例子 (Example)

我们可以通过排除end值来重写上面的例子,如下所示。 将以下内容保存在名为range_excluding_end.coffee的文件中

<b class="notranslate">numbers =[0...9]</b>
console.log "The contents of the range are:: "+ numbers 

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c ranges_example.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var numbers;
  numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8];
  console.log("The contents of the range are:: " + numbers);
}).call(this);

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

c:\> coffee ranges_example.coffee

执行时,CoffeeScript文件生成以下输出。 在这里,您可以观察到排除了最终值9

<b class="notranslate">The contents of the range are:: 0,1,2,3,4,5,6,7,8</b> 

使用带变量的范围

我们还可以通过为变量分配开始值和结束值来定义范围。

例子 (Example)

请考虑以下示例。 这里我们使用变量定义了一个范围。 将此代码保存在名为range_variables.coffee的文件中

start=0
end=9
numbers =[start..end]
console.log "The contents of the range are: "+ numbers

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c range_variables.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var end, i, numbers, results, start;
  start = 0;
  end = 9;
  numbers = (function() {
    results = [];
    for (var i = start; start <= end ? i <= end : i >= end; start <= end ? i++ : i--) {
      results.push(i);
    }
    return results;
  }).apply(this);
  console.log("The contents of the range are:: " + numbers);
}).call(this);

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

c:\> coffee range_variables.coffee

执行时,CoffeeScript文件生成以下输出。 在这里,您可以观察到排除了最终值9

The contents of the range are:: 0,1,2,3,4,5,6,7,8,9

阵列范围

我们可以通过使用范围对数组进行切片。 每当我们在数组(变量)之后立即指定范围时,CoffeeScript编译器就会将其转换为JavaScript的slice()方法调用。

假设我们有一个具有数值的数组,比如0到9,那么我们可以检索它的前4个元素,如下所示。

num  = [1, 2, 3, 4, 5, 6, 7, 8, 9]
data = num[0..5]

负值表示结尾的元素,例如,-1表示9.如果我们指定负数3后跟两个点,则将提取数组的最后三个元素。

data = num[-3..]

如果我们只在数组的范围内指定两个点作为num[..] ,那么将提取完整的数组。 我们还可以使用范围替换其他元素的数组段,如下所示。

num[2..6] = [13,14,15,16,17]

例子 (Example)

以下示例演示了使用带数组的范围。 将此代码保存在名为range_arrays.coffee的文件中

#slicing an array using ranges
num  = [1, 2, 3, 4, 5, 6, 7, 8, 9]
data = num[0..5]
console.log "The first four elements of the array : "+data
#Using negative values
data = num[-3..]
console.log "The last 3 elements of the array : "+data
#Extracting the whole array
console.log "Total elements of the array : "+num[..]
#Replacing the elements of an array
num[2..6] = [13,14,15,16,17]
console.log "New array : "+num 

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c range_arrays.coffee

在编译时,它为您提供以下JavaScript。 在这里,您可以观察到所有范围都转换为JavaScript的slice()方法调用。

// Generated by CoffeeScript 1.10.0
(function() {
  var data, num, ref;
  num = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  data = num.slice(0, 6);
  console.log("The first four elements of the array : " + data);
  data = num.slice(-3);
  console.log("The last 3 elements of the array : " + data);
  console.log("Total elements of the array : " + num.slice(0));
  [].splice.apply(num, [2, 5].concat(ref = [13, 14, 15, 16, 17])), ref;
  console.log("New array : " + num);
}).call(this); 

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

c:\> coffee range_arrays.coffee

执行时,CoffeeScript文件生成以下输出。 在这里,您可以观察到排除了最终值9

The first four elements of the array : 1,2,3,4,5,6
The last 3 elements of the array : 7,8,9
Total elements of the array : 1,2,3,4,5,6,7,8,9
New array : 1,2,13,14,15,16,17,8,9

带字符串的范围

我们也可以使用带字符串的范围。 如果我们在字符串之后指定范围,那么CoffeeScript会对它们进行切片并返回一个新的字符子集。

例子 (Example)

以下示例演示了使用字符串的范围。 这里我们创建了一个字符串,并使用范围从中提取了一个子字符串。 将此代码保存在名为ranges_with_strings.coffee的文件中

my_string = "Welcome to iowiki"
new_string = my_string[0..10]
console.log new_string

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c ranges_with_strings.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var my_string, new_string;
  my_string = "Welcome to iowiki";
  new_string = my_string.slice(0, 6);
  console.log(new_string);
}).call(this);

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

c:\> coffee ranges_with_strings.coffee

执行时,CoffeeScript文件生成以下输出。 在这里,您可以观察到排除了最终值9

Welcome to

对范围的理解

作为对象和数组,我们还可以使用理解来迭代范围的元素。

例子 (Example)

以下是使用范围内的理解的示例。 在这里,我们创建了一个范围,并使用理解检索其中的元素。 将此代码保存在名为comprehensions_over_ranges.coffee的文件中

numbers =[0..9]
console.log "The elements of the range are: "
console.log num for num in numbers

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c comprehensions_over_ranges.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var i, len, num, numbers;
  numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  console.log("The elements of the range are: ");
  for (i = 0, len = numbers.length; i < len; i++) {
    num = numbers[i];
    console.log(num);
  }
}).call(this);

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

c:\> coffee comprehensions_over_ranges.coffee

执行时,CoffeeScript文件生成以下输出。 在这里,您可以观察到排除了最终值9

The elements of the range are:
0
1
2
3
4
5
6
7
8

同样,我们也可以使用comprehension的by关键字来改变这个增量。

array = (num for num in [1..10] by 2)
console.log array

CoffeeScript - Splat

在前面的章节中,我们已经了解了如何定义函数并调用函数并将参数传递给它。 通常,我们可以将固定数量的参数传递给函数。 编程时,我们可能会面临需要将变量参数传递给这些函数的情况。 在JavaScript中,我们使用对象接受函数的可变数量的参数。

CoffeeScript提供了一个名为splats的功能,可以将多个参数传递给函数。 我们在函数中使用splats,在参数名称后放置三个点,并用...表示

语法 (Syntax)

下面给出了使用splats在函数内接受多个参数的语法。

my_function = (arguments...)->
   ............
   ............
   ............

例子 (Example)

以下是使用splats在函数内接受多个参数的示例。 这里我们使用indian_team()定义了一个名为indian_team()的函数。 我们将这个功能称为三次,我们每次调用时都会同时传递4名玩家,6名玩家和完整的小队。 由于我们在函数定义中使用了splats,因此每次调用它时它都接受可变数量的参数。 将此代码保存在名为splats_definition.coffee的文件中

indian_team = (first, second, others...) ->
  Captain = first
  WiseCaptain = second
  team  = others
  console.log "Captain: " +Captain
  console.log "Wise captain: " +WiseCaptain
  console.log "Other team members: " +team
#Passing 4 arguments
console.log "############## Four Players ############"
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma"
#Passing 6 arguments
console.log "############## Six Players ############"
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan"
#Passing full squad
console.log "############## Full squad #############"
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane"

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c splats_definition.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var indian_team,
    slice = [].slice;
  indian_team = function() {
    var Captain, WiseCaptain, first, others, second, team;
    first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? slice.call(arguments, 2) : [];
    Captain = first;
    WiseCaptain = second;
    team = others;
    console.log("Captain: " + Captain);
    console.log("Wise captain: " + WiseCaptain);
    return console.log("Other team members: " + team);
  };
  console.log("############## Four Players ############");
  indian_team("Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma");
  console.log("############## Six Players ############");
  indian_team("Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan");
  console.log("############## Full squad #############");
  indian_team("Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane");
}).call(this); 

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

c:\> coffee splats_definition.coffee

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

############## Four Players ############
Captain: Mahendra Singh Dhoni
Wise captain: Virat Kohli
Other team members: Shikhar Dhawan,Rohit Sharma
############## Six Players ############
Captain: Mahendra Singh Dhoni
Wise captain: Virat Kohli
Other team members: Shikhar Dhawan,Rohit Sharma,Gurkeerat Singh Mann,Rishi Dhawan
############## Full squad #############
Captain: Mahendra Singh Dhoni
Wise captain: Virat Kohli
Other team members: Shikhar Dhawan,Rohit Sharma,Gurkeerat Singh Mann,Rishi Dhawan,Ravindra Jadeja,Axar Patel,Jasprit Bumrah,Umesh Yadav,Harbhajan Singh,Ashish Nehra,Hardik Pandya,Suresh Raina,Yuvraj Singh,Ajinkya Rahane 

使用Splats调用函数

我们也可以使用splats调用函数。 为此,我们必须创建一个包含我们需要传递给函数的元素的数组,并且我们必须通过传递后缀为三个点的数组来调用该函数,如下所示。

my_function <b class="notranslate">values...</b>

例子 (Example)

以下是使用splats调用函数的示例。 将此代码保存在名为splats_call.coffee的文件中

indian_team = (first, second, others...) ->
  Captain = first
  WiseCaptain = second
  team  = others
  console.log "Captain: " +Captain
  console.log "Wise captain: " +WiseCaptain
  console.log "Other team members: " +team
squad = [
   "Mahendra Singh Dhoni"
   "Virat Kohli"
   "Shikhar Dhawan"
   "Rohit Sharma"   
   "Gurkeerat Singh Mann"
   "Rishi Dhawan"
   "R Ashwin"
   "Ravindra Jadeja"
   "Axar Patel"
   "Jasprit Bumrah"
   "Umesh Yadav"
   "Harbhajan Singh"
   "Ashish Nehra"
   "Hardik Pandya"
   "Suresh Raina"
   "Yuvraj Singh"
   "Ajinkya Rahane"
 ]
<b class="notranslate">indian_team squad...</b>

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c splats_call.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var indian_team, squad,
    slice = [].slice;
  indian_team = function() {
    var Captain, WiseCaptain, first, others, second, team;
    first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? slice.call(arguments, 2) : [];
    Captain = first;
    WiseCaptain = second;
    team = others;
    console.log("Captain: " + Captain);
    console.log("Wise captain: " + WiseCaptain);
    return console.log("Other team members: " + team);
  };
  squad = ["Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "R Ashwin", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane"];
  indian_team.apply(null, squad);
}).call(this);

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

c:\> coffee splats_call.coffee

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

Captain: Mahendra Singh Dhoni
Wise captain: Virat Kohli
Other team members: Shikhar Dhawan,Rohit Sharma,Gurkeerat Singh Mann,Rishi Dhawan,R Ashwin,Ravindra Jadeja,Axar Patel,Jasprit Bumrah,Umesh Yadav,Harbhajan Singh,Ashish Nehra,Hardik Pandya,Suresh Raina,Yuvraj Singh,Ajinkya Rahane

Splats with a Tailing Argument

我们还可以将拖尾参数传递给splats。 在下面给出的示例中,我们在splat之后传递了一个名为last的尾部参数。 将此示例保存在名为tailing_arguments.coffee的文件中

<b class="notranslate">indian_team = (first, second, others..., last) -></b>
  Captain = first
  WiseCaptain = second
  team  = others
  Wicketkeeper =last
  console.log "Captain: " +Captain
  console.log "Wise captain: " +WiseCaptain
  console.log "Wicket keeper is:"+last
  console.log "Other team members: " +team  
squad = [
   "Mahendra Singh Dhoni"
   "Virat Kohli"
   "Shikhar Dhawan"
   "Rohit Sharma"   
   "Gurkeerat Singh Mann"
   "Rishi Dhawan"
   "R Ashwin"
   "Ravindra Jadeja"
   "Axar Patel"
   "Jasprit Bumrah"
   "Umesh Yadav"
   "Harbhajan Singh"
   "Ashish Nehra"
   "Hardik Pandya"
   "Suresh Raina"
   "Yuvraj Singh"
   "Ajinkya Rahane"
 ]
indian_team squad...

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c tailing_arguments.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var indian_team, squad,
    slice = [].slice;
  indian_team = function() {
    var Captain, Wicketkeeper, WiseCaptain, first, i, last, others, second, team;
    first = arguments[0], second = arguments[1], others = 4 <= arguments.length ? slice.call(arguments, 2, i = arguments.length - 1) : (i = 2, []), last = arguments[i++];
    Captain = first;
    WiseCaptain = second;
    team = others;
    Wicketkeeper = last;
    console.log("Captain: " + Captain);
    console.log("Wise captain: " + WiseCaptain);
    console.log("Wicket keeper is:" + last);
    return console.log("Other team members: " + team);
  };
  squad = ["Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "R Ashwin", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane"];
  indian_team.apply(null, squad);
}).call(this);

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

c:\> coffee tailing_arguments.coffee

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

Captain: Mahendra Singh Dhoni
Wise captain: Virat Kohli
Wicket keeper is:Ajinkya Rahane
Other team members: Shikhar Dhawan,Rohit Sharma,Gurkeerat Singh Mann,Rishi Dhawan,R Ashwin,Ravindra Jadeja,Axar Patel,Jasprit Bumrah,Umesh Yadav,Harbhajan Singh,Ashish Nehra,Hardik Pandya,Suresh Raina,Yuvraj Singh

对Splats的理解

在函数中,我们还可以使用以下示例中所示的理解来迭代splat的元素。 将此代码保存在名为splats_comprehensions.coffee的文件中

indian_team = (first, second, others...) ->
  Captain = first
  WiseCaptain = second
  team  = others
  console.log "Captain: " +Captain
  console.log "Wise captain: " +WiseCaptain
  console.log "Other team members:: "
  console.log member for member in others
squad = [
   "Mahendra Singh Dhoni"
   "Virat Kohli"
   "Shikhar Dhawan"
   "Rohit Sharma"   
   "Gurkeerat Singh Mann"
   "Rishi Dhawan"
   "R Ashwin"
   "Ravindra Jadeja"
   "Axar Patel"
   "Jasprit Bumrah"
   "Umesh Yadav"
   "Harbhajan Singh"
   "Ashish Nehra"
   "Hardik Pandya"
   "Suresh Raina"
   "Yuvraj Singh"
   "Ajinkya Rahane"
 ]
indian_team squad...

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c splats_comprehensions.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var indian_team, squad,
    slice = [].slice;
  indian_team = function() {
    var Captain, WiseCaptain, first, i, len, member, others, results, second, team;
    first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? slice.call(arguments, 2) : [];
    Captain = first;
    WiseCaptain = second;
    team = others;
    console.log("Captain: " + Captain);
    console.log("Wise captain: " + WiseCaptain);
    console.log("Other team members:: ");
    results = [];
    for (i = 0, len = others.length; i < len; i++) {
      member = others[i];
      results.push(console.log(member));
    }
    return results;
  };
  squad = ["Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "R Ashwin", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane"];
  indian_team.apply(null, squad);
}).call(this);

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

c:\> coffee splats_comprehensions.coffee

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

Captain: Mahendra Singh Dhoni
Wise captain: Virat Kohli
Other team members::
Shikhar Dhawan
Rohit Sharma
Gurkeerat Singh Mann
Rishi Dhawan
R Ashwin
Ravindra Jadeja
Axar Patel
Jasprit Bumrah
Umesh Yadav
Harbhajan Singh
Ashish Nehra
Hardik Pandya
Suresh Raina
Yuvraj Singh
Ajinkya Rahane

CoffeeScript - Date

Date对象是JavaScript语言中内置的数据类型。 日期对象创建为new Date( )

创建Date对象后,可以使用许多方法对其进行操作。 大多数方法只允许您使用本地时间或UTC(通用或GMT)时间来获取和设置对象的年,月,日,小时,分钟,秒和毫秒字段。

ECMAScript标准要求Date对象能够在1970年1月1日之前或之后的1亿天内以毫秒精度表示任何日期和时间。 这是正负273,785年的范围,因此JavaScript可以表示直到275755年的日期和时间。

与其他JavaScript对象类似,我们也可以在CoffeeScript代码中使用日期对象。

日期方法

以下是JavaScript的Date对象的方法列表。 单击这些方法的名称以获取演示它们在CoffeeScript中的用法的示例。

S.No. 方法和描述
1 getDate()

根据当地时间返回指定日期的月中某天。

2 getDay()

根据当地时间返回指定日期的星期几。

3 getFullYear()

根据当地时间返回指定日期的年份。

4 getHours()

根据当地时间返回指定日期的小时。

5 getMilliseconds()

根据本地时间返回指定日期的毫秒数。

6 getMinutes()

根据当地时间返回指定日期的分钟数。

7 getMonth()

根据当地时间返回指定日期的月份。

8 getSeconds()

根据本地时间返回指定日期的秒数。

9 getTime()

返回指定日期的数值,作为自1970年1月1日00:00:00 UTC以来的毫秒数。

10 getTimezoneOffset()

返回当前语言环境的时区偏移量(以分钟为单位)。

11 getUTCDate()

根据通用时间返回指定日期中月份的日期(日期)。

12 getUTCDay()

根据通用时间返回指定日期的星期几。

13 getUTCFullYear()

根据通用时间返回指定日期的年份。

14 getUTCHours()

根据通用时间返回指定日期的小时数。

15 getUTCMinutes()

根据通用时间返回指定日期的毫秒数。

16 getUTCMilliseconds()

根据通用时间返回指定日期的分钟数。

17 getUTCMonth()

根据通用时间返回指定日期的月份。

18 getUTCSeconds()

根据通用时间返回指定日期的秒数。

19 getYear()

不推荐使用 - 根据当地时间返回指定日期的年份。 请改用getFullYear。

20 setDate()

根据当地时间设置指定日期的月中某天。

21 setFullYear()

根据当地时间设置指定日期的全年。

22 setHours()

根据当地时间设置指定日期的小时数。

23 setMilliseconds()

根据本地时间设置指定日期的毫秒数。

24 setMinutes()

根据当地时间设置指定日期的分钟数。

25 setMonth()

根据当地时间设置指定日期的月份。

26 setSeconds()

根据本地时间设置指定日期的秒数。

27 setTime()

将Date对象设置为自1970年1月1日00:00:00 UTC以来的毫秒数表示的时间。

28 setUTCDate()

根据通用时间设置指定日期的月中某天。

29 setUTCFullYear()

根据通用时间设置指定日期的全年。

30 setUTCHours()

根据通用时间设置指定日期的小时。

31 setUTCMilliseconds()

根据通用时间设置指定日期的毫秒数。

32 setUTCMinutes()

根据通用时间设置指定日期的分钟数。

33 setUTCMonth()

根据通用时间设置指定日期的月份。

34 setUTCSeconds()

根据通用时间设置指定日期的秒数。

35 setYear()

不推荐使用 - 根据当地时间设置指定日期的年份。 请改用setFullYear。

36 toDateString()

返回Date的“date”部分作为人类可读的字符串。

37 toLocaleDateString()

使用当前语言环境的约定,以字符串形式返回Date的“date”部分。

38 toLocaleString()

使用当前语言环境的约定将日期转换为字符串。

39 toLocaleTimeString()

使用当前语言环境的约定,以字符串形式返回Date的“time”部分。

40 toTimeString()

返回Date的“time”部分作为人类可读的字符串。

41 toUTCString()

使用通用时间约定将日期转换为字符串。

CoffeeScript - Math

JavaScript的Math对象为数学常量和函数提供了属性和方法。 与其他全局对象不同, Math不是构造函数。 Math所有属性和方法都是静态的,可以使用Math作为对象来调用而不创建它。

因此,您将常量pi称为Math.PI ,并将正弦函数称为Math.sin(x) ,其中x是方法的参数。 我们可以在CoffeeScript代码中使用JavaScript的Math对象来执行数学运算。

数学常数

如果我们想使用任何常见的数学常量,比如pi或e,我们可以使用JavaScript的Math对象来使用它们。

以下是JavaScript的Math对象提供的Math常量列表

S.No. 财产和描述
1

E

欧拉常数和自然对数的基数,约为2.718。

2

LN2

自然对数为2,约为0.693。

3

LN10

自然对数为10,约为2.302。

4

LOG2E

基数为2的对数,约为1.442。

5

LOG10E

基数为E的对数10,约为0.434。

6

PI

圆周长与直径之比约为3.14159。

7

SQRT1_2

平方根为1/2; 等价地,1平方根上的1,大约0.707。

8 SQRT2

平方根2,约1.414。

例子 (Example)

以下示例演示了CoffeeScript中JavaScript提供的数学常量的用法。 将此代码保存在名为math_example.coffee的文件中

e_value = Math.E
console.log "The value of the constant E is: " + e_value
LN2_value = Math.LN2
console.log "The value of the constant LN2 is: " + LN2_value
LN10_value = Math.LN10
console.log "The value of the constant LN10 is: " + LN10_value
LOG2E_value = Math.LOG2E
console.log "The value of the constant LOG2E is: " + LOG2E_value
LOG10E_value = Math.LOG10E
console.log "The value of the constant LOG10E is: " + LOG10E_value
PI_value = Math.PI
console.log "The value of the constant PI is: " + PI_value
SQRT1_2_value = Math.SQRT1_2
console.log "The value of the constant SQRT1_2 is: " + SQRT1_2_value
SQRT2_value = Math.SQRT2
console.log "The value of the constant SQRT2 is: " + SQRT2_value

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c math_example.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var LN10_value, LN2_value, LOG10E_value, LOG2E_value, PI_value, SQRT1_2_value, SQRT2_value, e_value;
  e_value = Math.E;
  console.log("The value of the constant E is: " + e_value);
  LN2_value = Math.LN2;
  console.log("The value of the constant LN2 is: " + LN2_value);
  LN10_value = Math.LN10;
  console.log("The value of the constant LN10 is: " + LN10_value);
  LOG2E_value = Math.LOG2E;
  console.log("The value of the constant LOG2E is: " + LOG2E_value);
  LOG10E_value = Math.LOG10E;
  console.log("The value of the constant LOG10E is: " + LOG10E_value);
  PI_value = Math.PI;
  console.log("The value of the constant PI is: " + PI_value);
  SQRT1_2_value = Math.SQRT1_2;
  console.log("The value of the constant SQRT1_2 is: " + SQRT1_2_value);
  SQRT2_value = Math.SQRT2;
  console.log("The value of the constant SQRT2 is: " + SQRT2_value);
}).call(this);

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

c:\> coffee math_example.coffee

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

The value of the constant E is: 2.718281828459045
The value of the constant LN2 is: 0.6931471805599453
The value of the constant LN10 is: 2.302585092994046
The value of the constant LOG2E is: 1.4426950408889634
The value of the constant LOG10E is: 0.4342944819032518
The value of the constant PI is: 3.141592653589793
The value of the constant SQRT1_2 is: 0.7071067811865476
The value of the constant SQRT2 is: 1.4142135623730951

数学方法

除了属性之外,Math对象还提供了方法。 以下是JavaScript的Math对象的方法列表。 单击这些方法的名称以获取演示它们在CoffeeScript中的用法的示例。

S.No. 方法和描述
1 abs()

返回数字的绝对值。

2 acos()

返回数字的反余弦(以弧度表示)。

3 asin()

返回数字的反正弦(以弧度表示)。

4 atan()

返回数字的反正切(以弧度表示)。

5 atan2()

返回其参数的商的反正切值。

6 ceil()

返回大于或等于数字的最小整数。

7 cos()

返回数字的余弦值。

8 exp()

返回E N ,其中N是参数,E是欧拉常数,是自然对数的基数。

9 floor()

返回小于或等于数字的最大整数。

10 log()

返回数字的自然对数(基数E)。

11 max()

返回零个或多个数字中的最大值。

12 min()

返回零个或多个数字中的最小值。

13 pow()

返回指数幂的基数,即基数指数。

14 random()

返回0到1之间的伪随机数。

15 round()

返回舍入到最接近整数的数字的值。

16 sin()

返回数字的正弦值。

17 sqrt()

返回数字的平方根。

18 tan()

返回数字的正切值。

CoffeeScript - Exception Handling

异常(或异常事件)是在执行程序期间出现的问题。 发生异常时,程序的正常流程中断,程序/应用程序异常终止,这是不推荐的,因此要处理这些异常。

出于许多不同的原因可能会发生异常。 以下是发生异常的一些情况。

  • 用户输入了无效数据。
  • 找不到需要打开的文件。

CoffeeScript中的例外情况

CoffeeScripts使用try catch and finally块支持异常/错误处理。 这些块的功能与JavaScript中的相同, try块保存异常语句, catch块具有在发生异常时要执行的操作, finally块用于无条件地执行语句。

以下是Try try catch的语法, finally是CoffeeScript中的块。

 try 
   // Code to run
 catch ( e ) 
   // Code to run if an exception occurs
 finally 
   // Code that is always executed regardless of 
   // an exception occurring

try块必须紧跟一个catch块或一个finally块(或两者之一)。 当try块中发生异常时,异常放在e并执行catch块。 在try/catch之后无条件执行可选的finally块。

例子 (Example)

以下示例演示了在CoffeeScript中使用try和catch块进行异常处理。 在这里,我们尝试在CoffeeScript操作中使用未定义的符号,并使用trycatch块处理发生的错误。 将此代码保存在名为Exception_handling.coffee的文件中

try
  x = y+20
  console.log "The value of x is :" +x
catch e
  console.log "exception/error occurred"
  console.log "The STACKTRACE for the exception/error occurred is ::"
  console.log e.stack

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c Exception_handling.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var e, error, x;
  try {
    x = y + 20;
    console.log("The value of x is :" + x);
  } catch (error) {
    e = error;
    console.log("exception/error occurred");
    console.log("The STACKTRACE for the exception/error occurred is ::");
    console.log(e.stack);
  }
}).call(this);

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

c:\> coffee Exception_handling.coffee

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

<b class="notranslate">exception/error occurred
The STACKTRACE for the exception/error occurred is :: </b>
ReferenceError: y is not defined
  at Object.<anonymous> (C:\Examples\strings_exceptions\Exception_handling.coffee:3:7)
  at Object.<anonymous> (C:\Examples\strings_exceptions\Exception_handling.coffee:2:1)
  at Module._compile (module.js:413:34)
  at Object.exports.run (C:\Users\IoWiki\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\coffee-script.js:134:23)
  at compileScript (C:\Users\IoWiki\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\command.js:224:29)
  at compilePath (C:\Users\IoWiki\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\command.js:174:14)
  at Object.exports.run (C:\Users\IoWiki\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\command.js:98:20)
  at Object.<anonymous> (C:\Users\IoWiki\AppData\Roaming\npm\node_modules\coffee-script\bin\coffee:7:41)
  at Module._compile (module.js:413:34)
  at Object.Module._extensions..js (module.js:422:10)
  at Module.load (module.js:357:32)
  at Function.Module._load (module.js:314:12)
  at Function.Module.runMain (module.js:447:10)
  at startup (node.js:139:18)
  at node.js:999:3

最后一块

我们也可以使用finally块重写上面的例子。 如果我们这样做,则在trycatch之后无条件地执行该块的内容。 将此代码保存在名为Exception_handling_finally.coffee的文件中

try
  x = y+20
  console.log "The value of x is :" +x
catch e
  console.log "exception/error occurred"
  console.log "The STACKTRACE for the exception/error occurred is ::"
  console.log e.stack
finally
  console.log "This is the statement of finally block"

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c Exception_handling_finally.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var e, error, x;
  try {
    x = y + 20;
    console.log("The value of x is :" + x);
  } catch (error) {
    e = error;
    console.log("exception/error occurred");
    console.log("The STACKTRACE for the exception/error occurred is ::");
    console.log(e.stack);
  } finally {
    console.log("This is the statement of finally block");
  }
}).call(this);

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

c:\> coffee Exception_handling_finally.coffee

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

<b class="notranslate">exception/error occurred
The STACKTRACE for the exception/error occurred is :: </b>
ReferenceError: y is not defined
  at Object.<anonymous> (C:\Examples\strings_exceptions\Exception_handling.coffee:3:7)
  at Object.<anonymous> (C:\Examples\strings_exceptions\Exception_handling.coffee:2:1)
  at Module._compile (module.js:413:34)
  at Object.exports.run (C:\Users\IoWiki\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\coffee-script.js:134:23)
  at compileScript (C:\Users\IoWiki\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\command.js:224:29)
  at compilePath (C:\Users\IoWiki\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\command.js:174:14)
  at Object.exports.run (C:\Users\IoWiki\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\command.js:98:20)
  at Object.<anonymous> (C:\Users\IoWiki\AppData\Roaming\npm\node_modules\coffee-script\bin\coffee:7:41)
  at Module._compile (module.js:413:34)
  at Object.Module._extensions..js (module.js:422:10)
  at Module.load (module.js:357:32)
  at Function.Module._load (module.js:314:12)
  at Function.Module.runMain (module.js:447:10)
  at startup (node.js:139:18)
  at node.js:999:3
This is the statement of finally block

throw 语句

CoffeeScript还支持throw语句。 您可以使用throw语句来引发内置异常或自定义异常。 稍后可以捕获这些异常,您可以采取适当的措施。

例子 (Example)

以下示例演示了CoffeeScript中throw语句的用法。 将此代码保存在名为throw_example.coffee的文件中

myFunc = ->
  a = 100
  b = 0
  try
    if b == 0
      throw ("Divided by zero error.")
    else
      c = a/b
  catch e
    console.log "Error: " + e
myFunc()

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c throw_example.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var myFunc;
  myFunc = function() {
    var a, b, c, e, error;
    a = 100;
    b = 0;
    try {
      if (b === 0) {
        throw "Divided by zero error.";
      } else {
        return c = a/b;
      }
    } catch (error) {
      e = error;
      return console.log("Error: " + e);
    }
  };
  myFunc();
}).call(this); 

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

c:\> coffee throw_example.coffee

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

Divided by zero error.

CoffeeScript - Regular Expressions

正则表达式是描述JavaScript支持的字符模式的对象。 在JavaScript中,RegExp类表示正则表达式,String和RegExp都定义了使用正则表达式在文本上执行强大的模式匹配和搜索和替换功能的方法。

CoffeeScript中的正则表达式

CoffeeScript中的正则表达式与JavaScript相同。 访问以下链接以查看JavaScript中的正则表达式javascript_regular_expressions

语法 (Syntax)

CoffeeScript中的正则表达式通过将RegExp模式放在正斜杠之间来定义,如下所示。

pattern =/pattern/

例子 (Example)

以下是CoffeeScript中正则表达式的示例。 在这里,我们创建了一个表达式,用于查找以粗体显示的数据(和 b>标记之间的数据)。 将此代码保存在名为regex_example.coffee的文件中

input_data ="hello how are you welcome to <b>IOWIKI.</b>"
regex = /<b>(.*)<\/b>/
result = regex.exec(input_data)
console.log result

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c regex_example.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var input_data, regex, result;
  input_data = "hello how are you welcome to <b>IOWIKI.</b>";
  regex = /<b>(.*)<\/b>/;
  result = regex.exec(input_data);
  console.log(result);
}).call(this);

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

c:\> coffee regex_example.coffee

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

[ '<b>IOWIKI.</b>',
  'IOWIKI.',
  index: 29,
  input: 'hello how are you welcome to <b> IOWIKI.</b>' ]

heregex

我们使用JavaScript提供的语法编写的复杂正则表达式是不可读的,因此为了使正则表达式更具可读性,CoffeeScript为称为heregex正则表达式提供了扩展语法。 使用这种语法,我们可以使用空格来破坏正常的正则表达式,我们也可以在这些扩展的正则表达式中使用注释,从而使它们更加用户友好。

例子 (Example)

以下示例演示了CoffeeScript heregex中高级正则表达式的heregex 。 在这里,我们使用高级正则表达式重写上面的示例。 将此代码保存在名为heregex_example.coffee的文件中

input_data ="hello how are you welcome to <b class="notranslate">IOWIKI.</b>"
heregex = ///
<b>  #bold opening tag 
(.*) #the tag value
</b>  #bold closing tag
///
result = heregex.exec(input_data)
console.log result

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c heregex_example.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var heregex, input_data, result;
  input_data = "hello how are you welcome to <b> IOWIKI.</b>";
  heregex = /<b>(.*) <\/b>/;
  result = heregex.exec(input_data);
  console.log(result);
}).call(this);

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

c:\> coffee heregex_example.coffee

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

[ '<b>IOWIKI.</b>',
  'IOWIKI.',
  index: 29,
  input: 'hello how are you welcome to <b>IOWIKI.</b>' ]

CoffeeScript - Classes and Inheritance

JavaScript不提供class关键字。 我们可以使用对象及其原型在JavaScript中实现继承。 每个对象都有自己的原型,并从原型继承功能和属性。 由于原型也是一个对象,它也有自己的原型。

尽管原型继承比经典继承强大得多,但对于新手用户来说却很困难和困惑。

CoffeeScript中的类

针对这个问题,CoffeeScript提供了一个基本结构,称为class ,它是使用JavaScript的原型构建的。 您可以使用class关键字在CoffeeScript中定义一个类,如下所示。

class Class_Name

例子 (Example)

考虑以下示例,这里我们使用关键字class创建了一个名为Studentclass

class Student
<p></p>

如果编译上面的代码,它将生成以下JavaScript。

var Student;
Student = (function() {
  function Student() {}
  return Student;
})();

实例化一个类

我们可以使用new运算符实例化一个类,就像其他面向对象的编程语言一样,如下所示。

new Class_Name

您可以使用new运算符实例化上面创建的(Student)类,如下所示。

class Student
new  Student

如果编译上面的代码,它将生成以下JavaScript。

var Student;
Student = (function() {
  function Student() {}
  return Student;
})();
new Student;

定义构造函数

构造函数是在实例化类时调用的函数,其主要目的是初始化实例变量。 在CoffeeScript中,您可以通过创建具有名称constructor函数的函数来定义构造函数,如下所示。

class Student
  constructor: (name)->
  @name = name

在这里,我们定义了一个构造函数,并将局部变量名称分配给实例变量。

@运算符是this关键字的别名,它用于指向类的实例变量。

如果我们在构造函数的参数之前放置@ ,那么它将自动设置为实例变量。 因此,上面的代码可以简单地写成如下所示 -

class Student
  constructor: (@name)->

例子 (Example)

以下是CoffeeScript中构造函数的示例。 将其保存在名为constructor_example.coffee的文件中

#Defining a class
class Student
  constructor: (@name)->
#instantiating a class by passing a string to constructor
student = new Student("Mohammed");
console.log "the name of the student is :"+student.name

Compiling the code

打开命令提示符并编译上面的示例,如下所示。

c:\>coffee -c constructor_example.coffee

在执行上述命令时,它将生成以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var Student, student;
  Student = (function() {
    function Student(name) {
      this.name = name;
    }
    return Student;
  })();
  student = new Student("Mohammed");
  console.log("The name of the student is :"+student.name);
}).call(this);

Executing the Code

通过在命令提示符下执行以下命令来运行上面的示例。

coffee constructor_example.coffee

在运行时,上面的示例为您提供以下输出。

The name of the student is :Mohammed

实例属性

与对象相同,我们也可以在类中具有属性。 这些被称为instance properties

例子 (Example)

请考虑以下示例。 在这里,我们在类中创建了变量(名称,年龄)和函数(message()),并使用其对象访问它们。 将此示例保存在名为instance_properties_example.coffee的文件中

#Defining a class
class Student
  name="Ravi"
  age=24
  message: ->
    "Hello "+name+" how are you" 
#instantiating a class by passing a string to constructor
student = new Student();
console.log student.message()

在编译时,上面的代码生成以下输出。

// Generated by CoffeeScript 1.10.0
(function() {
  var Student, student;
  Student = (function() {
    var age, name;
    function Student() {}
    name = "Ravi";
    age = 24;
    Student.prototype.message = function() {
      return "Hello " + name + " how are you";
    };
    return Student;
  })();
  student = new Student();
  console.log(student.message());
}).call(this);

静态属性

我们可以在类中定义静态属性。 静态属性的范围在类中受到限制,我们使用this keyword或其别名@符号创建静态函数,我们必须使用类名作为Class_Name.property来访问这些属性。

例子 (Example)

在下面的示例中,我们创建了一个名为message的静态函数。 并访问它。 将其保存在名为static_properties_example.coffee的文件中。

#Defining a class
class Student
  @message:(name) ->
    "Hello "+name+" how are you" 
console.log Student.message("Raju")

打开命令提示符并使用以下命令编译上述CoffeeScript文件。

c:\>coffee -c  static_properties_example.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var Student;
  Student = (function() {
    function Student() {}
    Student.message = function(name) {
      return "Hello " + name + " how are you";
    };
    return Student;
  })();
  console.log(Student.message("Raju"));
}).call(this);

在命令提示符下执行上面的coffeeScript,如下所示。

c:\>coffee static_properties_example.coffee

执行时,上面的示例为您提供以下输出。

Hello Raju how are you

继承 (Inheritance)

在CoffeeScript中,我们可以使用extends关键字继承另一个类中一个类的属性。

例子 (Example)

以下是CoffeeScript中的继承示例。 在这里,我们有两个类, AddMy_class 。 我们在类My_class中继承了名为Add的类的属性,并使用extends关键字访问它们。

#Defining a class
class Add
   a=20;b=30
   addition:->
     console.log "Sum of the two numbers is :"+(a+b) 
class My_class extends Add
my_class = new My_class()
my_class.addition()

CoffeeScript在幕后使用原型继承。 在CoffeeScript中,每当我们创建实例时,都会调用父类的构造函数,直到我们覆盖它为止。

我们可以使用super()关键字从子类调用父类的构造函数,如下面给出的示例所示。

#Defining a class
class Add
   constructor:(@a,@b) ->
   addition:=>
     console.log "Sum of the two numbers is :"+(@a+@b) 
class Mul extends Add
   constructor:(@a,@b) ->
     super(@a,@b)
   multiplication:->
     console.log "Product of the two numbers is :"+(@a*@b)
mul = new Mul(10,20)
mul.addition()
mul.multiplication()

动态类

CoffeeScript使用原型继承来自动继承类的所有实例属性。 这可以确保类是动态的; 即使您在创建子项后向父类添加属性,该属性仍将传播到其所有继承的子项。

class Animal
  constructor: (@name) ->
class Parrot extends Animal
Animal::rip = true
parrot = new Parrot("Macaw")
console.log "This parrot is no more" if parrot.rip

执行时,上面的CoffeeScript生成以下JavaScript代码。

// Generated by CoffeeScript 1.10.0
(function() {
  var Animal, Parrot, parrot,
    extend = function(child, parent) { for (var key in parent) {
      if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() {
      this.constructor = child; } ctor.prototype = parent.prototype;
      child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;
  Animal = (function() {
    function Animal(name) {
      this.name = name;
    }
    return Animal;
  })();
  Parrot = (function(superClass) {
    extend(Parrot, superClass);
    function Parrot() {
      return Parrot.__super__.constructor.apply(this, arguments);
    }
    return Parrot;
  })(Animal);
  Animal.prototype.rip = true;
  parrot = new Parrot("Macaw");
  if (parrot.rip) {
    console.log("This parrot is no more");
  }
}).call(this);  

CoffeeScript - Ajax

AJAX是一种用于创建交互式Web应用程序的Web开发技术。

  • AJAX代表A同步Ja vaScript和X ML。 它是一种借助XML,HTML,CSS和Java Script创建更好,更快,更交互的Web应用程序的新技术。

  • Ajax使用XHTML作为内容,CSS使用文档对象模型和JavaScript进行动态内容显示。

  • 传统的Web应用程序使用同步请求向服务器发送信息和从服 这意味着您填写表单,点击提交,然后从服务器获取包含新信息的新页面。

  • 使用AJAX,当您点击提交时,JavaScript将向服务器发出请求,解释结果并更新当前屏幕。 从最纯粹的意义上讲,用户永远不会知道任何东西甚至被传输到服务器。

  • XML通常用作接收服务器数据的格式,但可以使用任何格式(包括纯文本)。

  • AJAX是一种独立于Web服务器软件的Web浏览器技术。

  • 当客户端程序在后台请求来自服务器的信息时,用户可以继续使用该应用程序。

通常,我们使用jQuery来处理Ajax。 以下是Ajax和jQuery的示例

<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript"
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("#driver").click(function(event){
               $('#stage').load('/jquery/result.html');
            });
         });
      </script>
   </head>
   <body>
      <p>Click on the button to load /jquery/result.html file −</p>
      <div id = "stage" style = "background-color:cc0;">
         STAGE
      </div>
      <input type = "button" id = "driver" value = "Load Data" />
   </body>
</html>

这里load()向指定的URL /coffeescript/result.html文件发起Ajax请求。 加载此文件后,所有内容都将填充在标有ID stage “div”中。 假设我们的/jquery/result.html文件只有一行HTML -

<h1>THIS IS RESULT...</h1>

单击给定按钮时,将加载result.html文件。

新页面打开

使用Ajax的CoffeeScript

我们可以使用CoffeeScript重写上面的例子,如下所示。

<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript"
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script src="http://coffeescript.org/extras/coffee-script.js"></script>
      <script type="text/coffeescript">
        $(document).ready ->
          $('#driver').click (event) ->
            $('#stage').load '/jquery/result.html'
            return
          return
      </script>
   </head>
   <body>
      <p>Click on the button to load /jquery/result.html file -</p>
      <div id = "stage" style = "background-color:cc0;">
         STAGE
      </div>
      <input type = "button" id = "driver" value = "Load Data" />
   </body>
</html>

CoffeeScript - jQuery

jQuery是一个快速而简洁的库/框架,使用由John Resig在2006年创建的JavaScript构建,其中有一个很好的座右铭 - 写得少,做得更多。

jQuery简化了HTML文档遍历,事件处理,动画和Ajax交互,以实现快速Web开发。 访问我们的jQuery教程,了解jQuery

我们也可以使用CoffeeScript来处理jQuery 。 本章将教您如何使用CoffeeScript来使用jQuery。

使用CoffeeScript和jQuery

虽然jQuery解决了浏览器问题,但将它与JavaScript一起使用会产生一些不好的部分,这有点问题。 使用CoffeeScript而不是JavaScript是一个更好的主意。

在使用带有CoffeeScript的jQuery转换时,请记住以下几点。

$符号表示我们的应用程序中的jQuery代码。 使用它将jQuery代码与脚本语言分开,如下所示。

$(document).ready

除了在使用参数调用函数和处理模糊代码时,不需要在CoffeeScript中使用大括号,我们必须用箭头标记替换函数定义function() ,如下所示。

$(document).ready ->

删除不必要的return语句,因为CoffeeScript隐式返回函数的尾部语句。

例子 (Example)

以下是一个JavaScript代码,其中

元素正在被点击的元素之前插入 -
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("div").click(function () {
               $(this).before('<div class="div"></div>' );
            });
         });
      </script>
      <style>
         .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
      </style>
   </head>
   <body>
      <p>Click on any square below:</p>
      <span id = "result"> </span>
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
   </body>
</html>

现在,我们可以将上面的代码转换为CoffeeScript代码,如下所示

 <html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript"
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script src="http://coffeescript.org/extras/coffee-script.js"></script>
      <script type="text/coffeescript">
        $(document).ready ->
          $('div').click ->
            $(this).before '<div class="div"></div>'
            return
          return
      </script>
      <style>
         .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
      </style>
   </head>
   <body>
      <p>Click on any square below:</p>
      <span id = "result"> </span>
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
   </body>
</html>

执行时,这将为您提供以下输出。

新页面打开

什么是回调?

回调是函数的异步等价物。 在给定任务完成时调用回调函数。 Node大量使用回调。 编写Node的所有API都是为了支持回调。

例如,读取文件的函数可以开始读取文件并立即将控制返回到执行环境,以便可以执行下一条指令。 一旦文件I/O完成,它将在传递回调函数时调用回调函数,该文件的内容作为参数。 因此没有阻塞或等待文件I/O. 这使得Node.js具有高度可扩展性,因为它可以处理大量请求而无需等待任何函数返回结果。

阻止代码示例

创建一个名为input.txt的文本文件,其中包含以下内容

IOWIKI is giving self learning content 
to teach the world in simple and easy way!!!!! 

创建一个名为main.js的js文件,其中包含以下代码 -

var fs = require("fs");  
var data = fs.readFileSync('input.txt');  
console.log(data.toString()); 
console.log("Program Ended");

现在运行main.js来查看结果 -

$ node main.js

验证输出。

IOWIKI is giving self learning content 
to teach the world in simple and easy way!!!!! 
Program Ended

非阻塞代码示例

创建一个名为input.txt的文本文件,其中包含以下内容

IOWIKI is giving self learning content 
to teach the world in simple and easy way!!!!! 

更新main.js文件以获得以下代码 -

var fs = require("fs");  
fs.readFile('input.txt', function (err, data) { 
  if (err) return console.error(err); 
    console.log(data.toString()); 
}); 
console.log("Program Ended");

现在运行main.js来查看结果 -

$ node main.js 

验证输出。

Program Ended 
IOWIKI is giving self learning content 
to teach the world in simple and easy way!!!!!

这两个例子解释了blocking and non-blocking calls的概念。 第一个例子显示程序阻塞直到它读取文件,然后只是,它继续结束程序,而在第二个例子中,程序不等待文件读取,但它只是继续打印“程序结束”。

因此,阻塞程序按顺序执行。 从编程的角度来看,它更容易实现逻辑,但非阻塞程序不按顺序执行。 如果程序需要使用任何要处理的数据,则应将其保存在同一块中以使其顺序执行。

CoffeeScript - MongoDB

MongoDB是一个跨平台,面向文档的数据库,提供高性能,高可用性和易扩展性。 MongoDB适用于集合和文档的概念。 有关更多信息,请阅读我们的MongoDB教程

在本章中,您将学习如何使用CoffeeScript与MongoDB数据库进行通信。

安装 (Installation)

可以使用MongoDB的Node.js 2.0驱动程序将MongoDB数据库与CoffeeScript集成。 首先,您需要通过参考MongoDB教程的environment章节在系统中安装MongoDB。

安装MongoDB后成功浏览其bin文件夹(如果尚未设置路径)并启动MongoDB服务,如下所示。

C:\Program Files\MongoDB\Server\3.2\bin> mongod

最后通过在命令提示符中执行以下NPM命令来安装MongoDB驱动程序及其依赖项。

npm install mongodb --save

连接到MongoDB

为了连接到MongoDB,首先使用它创建MongoClient,调用connect()函数。 此函数接受url,并将回调函数作为参数。

以下CoffeeScript代码显示了如何连接到MongoDB服务器。 如果MongoDB服务器正在您的系统中运行,则此程序将建立与服务器的连接。

#Requiring the Mongodb package
mongo = require 'mongodb'
#Creating a MongoClient object
MongoClient = mongo.MongoClient
#Preparing the URL
url = 'mongodb://localhost:27017/testdb'
#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url
    #Close connection
    db.close()
  return

将上面的代码保存在名为connect_db.coffee的文件中,然后按如下所示执行。 如果成功创建了数据库,那么它将提供以下消息

c:\> coffee connect_db.coffee
coffee connect_db.collection
Connection established to mongodb://localhost:27017/testdb

创建一个集合

MongoDB中的集合包含我们存储在其中的文档。 您可以使用collection()函数创建集合。 此函数接受一个字符串参数,该参数表示我们要创建的集合的名称。

以下CoffeeScript代码显示了如何在MongoDB中创建集合。 如果有任何错误,它们将显示在控制台上。

#Requiring the Mongodb package
mongo = require 'mongodb'
#Creating a MongoClient object
MongoClient = mongo.MongoClient
#Preparing the URL
url = 'mongodb://localhost:27017/testdb'
#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url
    #Create collection
    col = db.collection('My_collection')
    console.log "Collection created successfully."
    #Close connection
    db.close()
  return

将上述代码保存在名为create_collection.coffee的文件中,然后按如下所示执行。 如果集合创建成功,那么它将给出以下消息

c:/> coffee create_collection.coffee
Connection established to mongodb://localhost:27017/testdb
Collection created successfully.

插入文件

您可以将文档嵌入到MongoDB中的集合中,您需要通过传递需要插入的文档列表作为参数来调用名为insert()的函数。

以下CoffeeScript代码显示了如何将文档插入名为My_collection的集合中。 如果有任何错误,它们将显示在控制台上。

#Sample JSON Documents
doc1 = {name: 'Ram', age: 26, city: 'Hyderabad'}
doc2 = {name: 'Rahim', age: 27, city: 'Banglore'}
doc3 = {name: 'Robert', age: 28, city: 'Mumbai'}
#Requiring the Mongodb package
mongo = require 'mongodb'
#Creating a MongoClient object
MongoClient = mongo.MongoClient
#Preparing the URL
url = 'mongodb://localhost:27017/testdb'
#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url  
  #Creating collection
  col = db.collection('My_collection')
  #Inserting documents
  col.insert [doc1,doc2,doc3], (err, result) ->
    if err
      console.log err
    else
      console.log "Documents inserted successfully"
    #Close connection
    db.close()
    return
  return

将上述代码保存在名为insert_documents.coffee的文件中,然后按如下所示执行。 如果成功插入文档,则会显示以下消息

c:/> coffee insert_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Documents inserted successfully

阅读文件

您可以使用名为find()的函数检索MongoDB中存储的文档。 以下CoffeeScript代码显示了如何检索存储在MongoDB中的记录。

#Requiring the Mongodb package
mongo = require 'mongodb'
#Creating a MongoClient object
MongoClient = mongo.MongoClient
#Preparing the URL
url = 'mongodb://localhost:27017/testdb'
#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url	
	#Creating collection object
    col = db.collection('My_collection')    
    #Inserting Documents
    col.find({name: 'Ram'}).toArray (err, result)->
      if err
        console.log err
      else 
      console.log 'Found:', result			
      #Closing connection
      db.close()
      return
  return

将上述代码保存在名为read_documents.coffee的文件中,然后按如下所示执行。 此程序检索指定集合中的所需文档,并显示如下所示。

C:\> coffee read_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ { _id: 56e269c10478809c3009ad1e,
    name: 'Ram',
    age: 26,
    city: 'Hyderabad' } ]

您还可以通过执行find()函数来读取特定集合中存在的所有文档,而不将任何参数传递给它,如下所示。

#Requiring the Mongodb package
mongo = require 'mongodb'
#Creating a MongoClient object
MongoClient = mongo.MongoClient
#Preparing the URL
url = 'mongodb://localhost:27017/testdb'
#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url	
	#Creating collection object
    col = db.collection('My_collection')    
    #Reading all Documents
    col.find().toArray (err, result)->
      if err
        console.log err
      else 
      console.log 'Found:', result			
      #Closing connection
      db.close()
      return
  return

将上述代码保存在名为read_all_documents.coffee的文件中,然后按如下所示执行。 此程序检索指定集合中的所有文档并显示如下所示。

C:\> coffee read_all_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ { _id: 56e2c5e27e0bad741a68c03e,
    name: 'Ram',
    age: 26,
    city: 'Hyderabad' },
  { _id: 56e2c5e27e0bad741a68c03f,
    name: 'Rahim',
    age: 27,
    city: 'Banglore' },
  { _id: 56e2c5e27e0bad741a68c040,
    name: 'Robert',
    age: 28,
    city: 'Mumbai' } ]

更新文件

您可以使用名为update()的函数update() MongoDB中存储的文档。 以下CoffeeScript代码显示了如何更新MongoDB中存储的记录。

#Get mongo client object
MongoClient = require('mongodb').MongoClient
#Connecting to mongodb
url = 'mongodb://localhost:27017/testdb'
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url	
	#Creating collection
    col = db.collection('My_collection')
    #Reading Data
    col.update {name:'Ram'},{$set:{city:'Delhi'}},(err, result)->
      if err
        console.log err
      else 
      console.log "Document updated"    
      #Closing connection
      db.close()
	  return
  return

该计划更新了从海得拉巴到德里的名为Ram的员工城市。

将上述代码保存在名为update_documents.coffee的文件中,然后按如下所示执行。 此程序检索指定集合中的文档并显示如下所示。

C:\> coffee update_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Document updated

更新后,如果执行read_documents.coffee程序,那么您将观察到名为Ram的人的城市名称从Hyderabad更新到Delhi

C:\> coffee Read_all_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ { _id: 56e2c5e27e0bad741a68c03e,
    name: 'Ram',
    age: 26,
    city: 'Delhi' },
  { _id: 56e2c5e27e0bad741a68c03f,
    name: 'Rahim',
    age: 27,
    city: 'Banglore' },
  { _id: 56e2c5e27e0bad741a68c040,
    name: 'Robert',
    age: 28,
    city: 'Mumbai' } ]

删除文件

您可以使用remove()函数remove()集合中的所有文档。 以下CoffeeScript代码显示了如何删除MongoDB中存储的所有记录。

#Get mongo client object
MongoClient = require('mongodb').MongoClient
#Connecting to mongodb
url = 'mongodb://localhost:27017/testdb'
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url	
	#Creating collection
    col = db.collection('My_collection')
    #Deleting Data
    col.remove()
    console.log "Document deleted"
    #Closing connection
    db.close()	  
  return

将上述代码保存在名为delete_documents.coffee的文件中,然后按如下所示执行。 此程序将删除指定集合中显示以下消息的所有文档。

C:\> coffee delete_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Document deleted

删除后,如果执行read_documents.coffee程序,则会得到一个空集合,如下所示。

C:\> coffee Read_all_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ ]

CoffeeScript - SQLite

SQLite是一种基于模式的轻量级关系数据库引擎。 它是用于Web浏览器中本地存储的嵌入式数据库软件的流行选择。

与许多其他数据库管理系统不同,SQLite不是客户端 - 服务器数据库引擎。 有关更多信息,请阅读我们的SQLite教程

在本章中,您将学习如何使用CoffeeScript与SQLite数据库进行通信。

安装 (Installation)

可以使用node-sqlite3模块将SQLite3数据库与CoffeeScript集成。 此模块适用于Node.js v0.10.x,v0.12.x,v4.x和v5.x. 该模块提供各种功能,使用CoffeeScript与SQLite3进行通信,此外,它还提供了简单的查询和参数绑定接口,以及查询序列化API。

您可以使用npm安装node-sqlite3模块,如下所示。

npm install sqlite3

要使用sqlite3模块,必须首先创建一个表示数据库的连接对象,该对象将帮助您执行所有SQL语句。

连接到数据库 (Connecting to Database)

为了连接到SQLite数据库,首先通过调用node-sqlite3模块的require()函数创建其包,并将字符串sqlite3作为参数传递给它。 然后通过将数据库的名称传递给sqlite3.Database()构造来连接到数据库。

以下CoffeeScript代码显示了如何连接到现有数据库。 如果数据库不存在,那么它将使用给定名称test.db创建,打开,最后将返回数据库对象。

#Creating sqlite3 package
sqlite3 = require('sqlite3')
#Creating a Database instance
db = new (sqlite3.Database)('test.db')
console.log "Database opened successfully."

我们还可以提供:memory:创建一个匿名的内存数据库,一个空字符串来创建匿名的基于磁盘的数据库,而不是test.db. 将上面的代码保存在名为create_db.coffee的文件中,然后执行它,如下所示。 如果数据库成功创建,那么它将产生以下消息 -

c:\> coffee create_db.coffee
Successfully connected

创建表

您可以使用run()函数通过CoffeeScript在SQLite数据库中创建表。 传递查询以String格式创建此函数的表。

以下CoffeeScript程序将用于在以前的test.db数据库中创建表 -

#Creating sqlite3 package
sqlite3 = require('sqlite3')
#Creating a Database instance
db = new (sqlite3.Database)('test.db')
console.log "Successfully connected"
db.serialize ->
  db.run 'CREATE TABLE STUDENT (name TEXT, age INTEGER, city TEXT)'
  console.log "Table created successfully"  
  return
db.close()

serialize()函数以序列化模式设置数据库。 在此模式下,当遇到回调时,将立即调用它。 该回调中的查询是串行执行的。 很快函数返回数据库将再次设置为正常模式。 完成事务后,我们需要使用close()函数关闭连接。

将上述代码保存在名为create_table.coffee的文件中,然后按如下所示执行。 这将在数​​据库test.db创建一个名为STUDENT的表,显示以下消息。

C:\> coffee create_table.coffee
Successfully connected
Table created successfully

插入/创建数据

您可以通过执行insert语句通过CoffeeScript代码将数据插入SQLite数据库。 为此,我们可以使用prepare()函数来准备SQL语句。

它还接受带有绑定变量( ? )的查询,可以使用run()函数附加这些变量的值。 您可以使用预准备语句插入多个记录,并在插入所有记录后,需要使用finalize()函数完成预准备语句。

以下CoffeeScript程序显示如何在上一个示例中创建的名为STUDENT的表中插入记录。

#Creating sqlite3 package
sqlite3 = require('sqlite3').verbose()
#Creating a Database instance
db = new (sqlite3.Database)('test.db')
console.log "Successfully connected"
db.serialize ->
  stmt = db.prepare('INSERT INTO STUDENT VALUES (?,?,?)')
  stmt.run 'Ram',24,'Hyderabad'
  stmt.run 'Robert',25,'Mumbai'
  stmt.run 'Rahim',26,'Bangalore'
  stmt.finalize()
  console.log "Data inserted successfully"
  return
db.close()

将上面的代码保存在名为insert_data.coffee的文件中,然后按如下所示执行。 这将填充名为STUDENT的表,显示以下消息。

C:\> coffee insert_data.coffee
Successfully connected
Data inserted successfully

阅读/检索数据

您可以使用each()函数从SQLite表中获取数据。 此函数接受一个可选的回调函数,该函数将在每一行上调用。

以下CoffeeScript程序显示了我们如何从上一个示例中创建的名为STUDENT的表中获取和显示记录

#Creating sqlite3 package
sqlite3 = require('sqlite3').verbose()
#Creating a Database instance
db = new (sqlite3.Database)('test.db')
console.log "Successfully connected"
db.serialize ->
  console.log "The contents of the table STUDENT are ::"
  db.each 'SELECT rowid AS id, name,age,city FROM STUDENT', (err, row) ->
    console.log row.id + ': ' +row.name+', '+ row.age+', '+ row.city
    return
  return
db.close()

将上述代码保存在名为retrive_data.coffee的文件中,然后按如下所示执行。 这将检索名为STUDENT的表中的所有记录,并在控制台上显示如下。

C:\> coffee retrive_data.coffee
Successfully connected
The contents of the table STUDENT are ::
1: Ram, 24, Hyderabad
2: Robert, 25, Mumbai
3: Rahim, 26, Bangalore

更新数据

以下CoffeeScript代码显示了如何使用UPDATE语句更新任何记录,然后在名为STUDENT的表中获取并显示更新的记录

#Creating sqlite3 package
sqlite3 = require('sqlite3').verbose()
#Creating a Database instance
db = new (sqlite3.Database)('test.db')
console.log "Successfully connected"
db.serialize ->
  #Updating data
  stmt = db.prepare('UPDATE STUDENT SET city = ? where name = ?')
  stmt.run 'Delhi','Ram'
  console.log "Table updated"
  stmt.finalize()
  #Retrieving data after update operation
  console.log "The contents of the table STUDENT after update operation are ::"
  db.each 'SELECT rowid AS id, name, city FROM STUDENT', (err, row) ->
    console.log row.id + ': ' +row.name+', '+ row.city
    return
  return
db.close()

将上述代码保存在名为update_data.coffee的文件中,然后按如下所示执行。 这将更新名为Ram的学生的城市,并在更新操作后显示表中的所有记录,如下所示。

C:\> coffee update_data.coffee
Successfully connected
Table updated
The contents of the table STUDENT after update operation are ::
1: Ram, Delhi
2: Robert, Mumbai
3: Rahim, Bangalore

删除数据

以下CoffeeScript代码显示了如何使用DELETE语句删除任何记录,然后从名为STUDENT的表中获取并显示剩余记录。

#Creating sqlite3 package
sqlite3 = require('sqlite3').verbose()
#Creating a Database instance
db = new (sqlite3.Database)('test.db')
console.log "Successfully connected"
db.serialize ->
  #Deleting data
  stmt = db.prepare('DELETE FROM STUDENT WHERE name = ?')
  stmt.run 'Ram'
  console.log "Record deleted"
  stmt.finalize()
  #Retrieving data after delete operation
  console.log "The contents of the table STUDENT after delete operation are ::"
  db.each 'SELECT rowid AS id, name, city FROM STUDENT', (err, row) ->
    console.log row.id + ': ' +row.name+', '+ row.city
    return
  return
db.close()

将上述代码保存在名为delete_data.coffee的文件中,然后按如下所示执行。 它删除名为Ram的学生的记录,并在删除操作后显示表中的所有剩余部分,如下所示。

Successfully connected
Record deleted
The contents of the table STUDENT after delete operation are ::
2: Robert, Mumbai
3: Rahim, Bangalore
↑回到顶部↑
WIKI教程 @2018