Coffeescript 简明教程

CoffeeScript - Quick Guide

CoffeeScript - Overview

目前,JavaScript 是最快的主流动态语言,它被誉为 Web 的通用语。它是由 Brendan Eich 在 1995 年的 10 天内开发的。

At present, JavaScript is the fastest mainstream dynamic language available, and it is known as the lingua franca of the web. It is developed by Brendan Eich in the year of 1995 in 10 days.

由于其有效的功能,JavaScript 变得流行,并迅速风靡全球。它在实验室中存在的时间非常短暂,不足以对该语言进行完善。也许正是出于这个原因,尽管 JavaScript 有好的部分,但它仍然存在大量的设计错误,并且因其古怪而获得了恶名。

Because of its effective features, JavaScript became popular and went global quickly. It was there in lab for a very less time, which was not enough to polish the language. May be for this reason, inspite of its good parts, JavaScript has a bunch of design errors and it bagged a bad reputation of being a quirky language.

What is CoffeeScript ?

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

CoffeeScript is a lightweight language based on Ruby and Python which transcompiles (compiles from one source language to another) into JavaScript. It provides better syntax avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language.

Advantages of CoffeeScript

以下是 CoffeeScript 的优势 −

Following are the advantages of CoffeeScript −

  1. Easily understandable − CoffeeScript is a shorthand form of JavaScript, its syntax is pretty simple compared to JavaScript. Using CoffeeScript, we can write clean, clear, and easily understandable codes.

  2. Write less do more − For a huge code in JavaScript, we need comparatively very less number of lines of CoffeeScript.

  3. Reliable − CoffeeScript is a safe and reliable programming language to write dynamic programs.

  4. Readable and maintainable − CoffeeScript provides aliases for most of the operators which makes the code readable. It is also easy to maintain the programs written in CoffeeScript.

  5. Class-based inheritance − JavaScript does not have classes. Instead of them, it provides powerful but confusing prototypes. Unlike JavaScript, we can create classes and inherit them in CoffeeScript. In addition to this, it also provides instance and static properties as well as mixins. It uses JavaScript’s native prototype to create classes.

  6. No var keyword − There is no need to use the var keyword to create a variable in CoffeeScript, thus we can avoid the accidental or unwanted scope deceleration.

  7. Avoids problematic symbols − There is no need to use the problematic semicolons and parenthesis in CoffeeScript. Instead of curly braces, we can use whitespaces to differentiate the block codes like functions, loops, etc.

  8. Extensive library support − In CoffeeScript, we can use the libraries of JavaScript and vice versa. Therefore, we have access to a rich set of libraries while working with CoffeeScript.

History of CoffeeScript

  1. CoffeeScript is developed by Jeremy Ashkenas. It was first committed in Git On December 13, 2009.

  2. Originally the compiler of the CoffeeScript was written in Ruby language.

  3. In March 2010, the CoffeeScript compiler was replaced; this time instead of Ruby, they used CoffeeScript itself.

  4. And in the same year, CoffeeScript 1.0 was released and at the time of release, it was one of the most wanted projects of the Git hub.

Limitations of CoffeeScript

  1. Sensitive to whitespaces − CoffeeScript is very sensitive to whitespaces, so programmers need to be very careful while providing indentations. If we do not maintain proper indentation, the entire code may go wrong.

TutorialsPoint’s CoffeeScript IDE

你可以使用 TutorialsPoint 在我们的编码基础部分提供的 CoffeeScript 编译器来编译 CoffeeScript 文件 https://www.tutorialspoint.com/codingground.htm 。按照以下步骤使用我们的 CoffeeScript 编译器。

You can compile CoffeeScript files using TutorialsPoint’s CoffeeScript compiler provided in our Coding Ground section https://www.tutorialspoint.com/codingground.htm. Follow the steps given below to use our CoffeeScript compiler.

Step 1

点击以下链接,访问我们网站的主页 www.tutorialspoint.com

Visit the home page of our website by clicking the following link www.tutorialspoint.com.

Step 2

在主页右上角单击名为 CODING GROUND 的按钮,如下面给出的快照中所示。

Click on the button named CODING GROUND that is located at the top right corner of the homepage as highlighted in the snapshot given below.

tutorialspoint homepage

Step 3

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

This will lead to our CODING GROUND section which provides online terminals and IDEs for about 135 programming languages. Open CoffeeScript IDE in the Online IDEs section which is shown in the following snapshot.

coding ground

Step 4

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

If you paste your CoffeeScript code in main.coffee (You can change the file name) and click the Preview button, then you can see the compiled JavaScript in the console as shown in the following snapshot.

tp coffeescript ide

CoffeeScript - Environment

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

The Compiler of the latest versions of CoffeeScript is written in CoffeeScript itself. To run CoffeeScript files in your system without a browser, you need a JavaScript runtime.

Node.js

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

Node.js is a JavaScript framework which is used to develop network server applications. It also acts as a bridge between JavaScript and the Operating System.

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

The command-line version of CoffeeScript is distributed as a Node.js package. Therefore, to install CoffeeScript (command-line) in your system, you first need to install node.js.

Installing Node.js

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

Here are the steps to download and install Node.js in your system.

Step 1

访问 nodejs homepage ,并通过单击下面快照中标亮的按钮下载其适用于 Windows 的稳定版本。

Visit the nodejs homepage and download its stable version for windows by clicking on the button hilighted in the snapshot given below.

homepage

Step 2

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

On clicking, a .msc file named node-v5.50-x64 will be downloaded into your system, run the downloaded file to start the Node.js set-up. Here is the snapshot of the Welcome page of Node.js set-up wizard.

click next

Step 3

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

Click on the Next button in the Welcome page of the Node.js set-up wizard which will lead you to the End-user License Agreement page. Accept the license agreement and click on the Next button as shown below.

license agreement

Step 4

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

On the next page, you need to set the destination folder to the path where you want to install Node.js. Change the path to the required folder and click on the Next button.

set destination folder

Step 5

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

In the Custom setup page, select the Node.js runtime to install node.exe file and click Next.

custom setup

Step 6

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

Finally, click on the Install button which will start the Node.js installation.

click install

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

Click on the Finish button of the Node.js set-up wizard as shown below to complete the Node.js installation.

click finish

Installing CoffeeScript

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

Node.js provides you a command prompt (Node.js command prompt). You can install CoffeeScript globally by entering the following command in it.

c:\> npm install -g coffeescript

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

On executing the the above command, CoffeeScript will be installed in your system by producing the following output.

install coffeescript

Verification

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

You can verify the installation of the CoffeeScript by typing the following command.

c:\> coffee -v

成功安装时,此命令会向你提供 CoffeeScript 版本,如下所示。

On successful installation, this command gives you the version of CoffeeScript as shown below.

verification

CoffeeScript - Command-line utility

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

On installing CoffeeScript on Node.js, we can access the coffee-command line utility. In here, the coffee command is the key command. Using various options of this command, we can compile and execute the CoffeeScript files.

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

You can see the list of options of the coffee command using its -h or --help option. Open the Node.js command prompt and execute the following command in it.

c:\>coffee -help

此命令会给您 coffee 的各种选项列表,以及其中每个选项执行的操作的说明,如下所示。

This command gives you the list of various options of the coffee, along with the description of the operation performed by each of them as shown below.

coffeecommand help

Compiling the CoffeeScript Code

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

The CoffeeScript files are saved with the extension .coffee. You can compile these files using the -c or --compile option of the coffee command as shown below.

c:\>coffee -c filename.coffee

Example

假设您的系统中有一个包含以下 CoffeeScript 代码的文件,该代码会在控制台上打印一条消息。

Suppose there is a file in your system with the following CoffeeScript code which prints a message on the console.

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

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

Note − The console.log() function prints the given string on the console.

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

To compile the above code, save it in a file with the name sample.coffee. Open the Node.js command prompt. Browse through the path where you have saved the file and compile it using the -c option of the coffee command of the coffee command-line utility as shown below.

c:\> coffee -c sample.coffee

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

On executing the above command, the CoffeeScript compiler compiles the given file (sample.coffee) and saves it in the current location with a name sample.js as shown below.

js file

若你打开 sample.js 文件,便可观察到生成的 JavaScript,如下所示。

If you open the sample.js file, you can observe the generated JavaScript as shown below.

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

}).call(this);

Executing the CoffeeScript code

你可以通过在 Node.js 命令提示符中将文件名传递给 coffee 命令,轻松执行 CoffeeScript 文件,如下所示。

You can execute a CoffeeScript file by simply passing the file name to the coffee command in the Node.js command prompt as follows.

c:\> coffee sample.coffee

Example

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

For example, let us execute the sample.coffee file. For this, open the Node.js command prompt. Browse through the path where you have saved the file and execute the file by directly passing its name to the coffee command as shown below.

execution

Watch and Compile

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

In some scenarios, there is a chance that we do a lot of changes to our scripts. Using the –w option of the coffee command, you watch your scripts for changes.

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

You can watch and compile a file simultaneously using the -wc option as shown below. When we use this option, the file will be recompiled each time you make changes in your script.

c:\>coffee -wc file_name

Example

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

Suppose we have compiled a file named sample.coffee using the -wc option and we modified the script thrice. Each time we change the script, the .coffee file is recompiled leaving the Node.js command prompt as shown below.

watch and compile

Setting the Output Directory

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

Using the -o option, we can set the output directory to place the compiled JavaScript files as shown below.

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

Example

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

Let us save the JavaScript code of the sample.coffee file in a folder named data in the E drive using the -o option by executing the following command in the command prompt.

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

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

Following is the snapshot of the given folder after executing the above command. Here you can observe the JavaScript file of the sample.coffee

output directory

Print the Compiled JavaScript

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

If we want to print the compiled javascript on the console itself, we have to use the -p option of the coffee command as shown below.

c:\>coffee -p file_name

Example

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

For example, you can print the compiled JavaScript code of the sample.coffee file on the console using the -p option as shown below.

print javascript

The REPL (Read Evaluate Print Loop)

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

CoffeeScript provides you an REPL-interactive shell. This shell is used to evaluate the CoffeeScript expressions. You can type any CoffeeScript code in this shell and get the result immediately. You can open REPL by executing the coffee command without any options as shown below.

execute coffee command

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

Using this shell, we can assign values to variables, create functions, and evaluate results. As shown in the following screenshot, if we call functions in REPL, it prints the value of the function. If we give an expression to it, it evaluates and prints the result of the expression. And if we simply type the statements in it, it prints the value of the last statement.

repl usage

在 REPL 中,你可以通过按 ctrl+v 访问多行模式,在多行模式中,你可以使用多行 (如函数) 来评估代码,并且你可以通过再次按 ctrl+v 从中返回到 REPL 模式。下面是多行模式使用的一个示例。

In REPL, you can access multiple line mode by pressing ctrl+v where you can evaluate the code with multiple lines (like functions) and you can get back to REPL mode from it by pressing ctrl+v again. Here is an example usage of the multi line mode.

repl multilinefunction

Running CoffeeScript through Browser

我们可以像 JavaScript 一样使用 HTML 的 <script> 标签运行 CoffeeScript,如下所示。

We can run CoffeeScript using the <script> tag of the HTML just like JavaScript as shown below.

<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 代码会逐行解释。这将减慢你的应用程序的速度,因此不建议使用此方法。

But for this, we have to import the library in each application and the CoffeeScript code will be interpreted line by line before the output is shown. This will slow down your applications, therefore this approach is not recommended.

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

Therefore, to use CoffeeScript in your applications, you need to pre-compile them using the Coffee command-line utility and then you can use the generated JavaScript in your applications.

CoffeeScript - Syntax

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

In the previous chapter, we have seen how to install CoffeeScript. In this chapter, let us check out the syntax of CoffeeScript.

  • * *与JavaScript的语法相比,CoffeeScript的语法更优雅。它避免了像花括号、分号和变量减速这样的麻烦特性。

The syntax of CoffeeScript is more graceful when compared to the syntax of JavaScript. It avoids the troublesome features like curly braces, semicolons, and variable decelerations.

CoffeeScript Statements

  • * *与C、C++和Java等许多其他编程语言不同,CoffeeScript中的语句并不以分号 (;) 结尾。相反,CoffeeScript编译器将每一行都视为一个单独的语句。

Unlike many other programming languages like C, C++, and Java, the statements in CoffeeScript do not end with semicolons (;). Instead of that, every new line is considered as a separate statement by the CoffeeScript compiler.

Example

  • * *这里有一个CoffeeScript语句的例子。

Here is an example of a CoffeeScript statement.

name = "Javed"
age = 26
  • * *以同样的方式,我们可以使用分号将两条语句写在单行中,如下所示。

In the same way, we can write two statements in a single line by separating them using semicolon as shown below.

name = "Javed";age = 26

CoffeeScript Variables (No var Keyword)

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

In JavaScript, we declare a variable using the var keyword before creating it, as shown below.

var name = "Javed"
var age = 20
  • * 在CoffeeScript中创建变量时,不需要使用 *var 关键字来声明变量。我们只需通过给它赋值来直接创建变量,如下所示。

While creating variables in CoffeeScript, there is no need to declare them using the var keyword. We can directly create a variable just by assigning a value to it as shown below.

name = "Javed"
age = 20

No Parentheses

  • * 通常,我们在声明函数、调用函数以及分隔代码块时使用括号以避免歧义。在CoffeeScript中,不需要使用括号,而在创建函数时,我们使用箭头标记 ( *→ ) 代替括号,如下所示。

In general, we use parenthesis while declaring the function, calling it, and also to separate the code blocks to avoid ambiguity. In CoffeeScript, there is no need to use parentheses, and while creating functions, we use an arrow mark () instead of parentheses as shown below.

myfunction = -> alert "Hello"
  • * *不过,在某些情况下,我们仍然必须使用括号。在调用没有参数的函数时,我们将使用括号。例如,如果我们在CoffeeScript中有一个名为my_function的函数,那么我们必须按照如下所示调用它。

Still, we have to use parentheses in certain scenarios. While calling functions without parameters, we will use parentheses. For example, if we have a function named my_function in CoffeeScript, then we have to call it as shown below.

my_function()
  • * *以同样的方式,我们也可以使用括号来分隔模棱两可的代码。如果你观察以下示例,没有大括号,结果是2233,有括号,结果是45。

In the same way, we can also separate the ambiguous code using parentheses. If you observe the following example, without braces, the result is 2233 and with braces, it will be 45.

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

No Curly Braces

  • * *在JavaScript中,对于诸如函数、循环和条件语句之类的块代码,我们使用大括号。在CoffeeScript中,不需要使用大括号。相反,我们必须在正文中保持适当的缩进(空格)。这是受Python语言启发的特性。

In JavaScript, for the block codes such as functions, loops, and conditional statements, we use curly braces. In CoffeeScript, there is no need to use curly braces. Instead, we have to maintain proper indentations (white spaces) within the body. This is the feature which is inspired from the Python language.

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

Following is an example of a function in CoffeeScript. Here you can observe that instead of curly braces, we have used three whitespaces as indentation to separate the body of the function.

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

CoffeeScript Comments

  • * *在任何编程语言中,我们使用注释来编写我们编写的代码的描述。这些注释不被认为是程序的一部分。CoffeeScript中的注释类似于Ruby语言的注释。CoffeeScript提供了两种类型的注释,如下所述 −

In any programming language, we use comments to write description about the code we have written. These comments are not considered as the part of the programs. The comments in CoffeeScript are similar to the comments of Ruby language. CoffeeScript provides two types of comments as follows −

Single-line Comments

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

Whenever we want to comment a single line in CoffeeScript, we just need to place a hash tag before it as shown below.

# This is the single line comment in CoffeeScript

在 CoffeeScript 编译器中,每个单行标记后 ( # ) 的行都被视为注释,它将编译给定文件中未注释的其余代码。

Every single line that follows a hash tag (#) is considered as a comment by the CoffeeScript compiler and it compiles the rest of the code in the given file except the comments.

Multiline Comments

当我们希望在 CoffeeScript 中注释多行(多行)时,我们可以通过将这些行包裹在对三重井号标记中来实现,如下所示。

Whenever we want to comment more than one line in CoffeeScript (multiple lines), we can do that by wrapping those lines within a pair of triple hash tags as shown below.

###
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 Reserved keywords

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

A list of all the reserved words in CoffeeScript are given in the following table. They cannot be used as CoffeeScript variables, functions, methods, loop labels, or any object names.

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 Data Types

编程语言最重要的特性之一是它支持的数据类型集。这些类型的值可以在编程语言中表示和操纵。

One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.

CoffeeScript 逐行编译为 JavaScript,因此 CoffeeScript 提供的数据类型与 JavaScript 相同。除了 CoffeeScript 增加了某种额外精髓的事实。

As CoffeeScript compiles line by line to JavaScript, the data types provided by CoffeeScript are same as JavaScript. Except for the fact that CoffeeScript adds some additional essence.

CoffeeScript 提供了下列数据类型供使用 −

CoffeeScript provides the following data types to work with −

  1. Strings − The String data type represents a group of characters in general and we represent a string value with in-between double quotes (" "). Example: "Raj", "Rahman"

  2. Number − The number data type represents the numerical values. Example: 12, 212, etc.

  3. Boolean − Boolean data type represents one bit of information. There are only two possible values: true and false.

  4. Arrays − The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. Example: student = ["Rahman","Ramu","Ravi","Robert"]

  5. Objects − The Objects in CoffeeScript are similar to those in JavaScript these are collection of the properties. Where a property includes a key and a value separated by a semi colon (:). In short, CoffeeScript objects are a collection of key-value pairs. Example: student = {name: "Mohammed", age: 24, phone: 9848022338 }

  6. Null − A variable that is defined and does not hold any value is considered and null. This is similar to the null value in JavaScript.

  7. Undefined − A variable which hasn’t had any value assigned to it is considered as undefined variable. If you use such variables in your code, then you will get an undefined error.

我们将在单独章节中详细介绍数据类型数组和对象。

We will cover the data types Arrays and Objects in detail in separate chapters.

CoffeeScript - Variables

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

Variables are nothing but named containers. You can place data into these containers and then refer to the data using the name of its container.

CoffeeScript Variables

在 JavaScript 中,在使用变量之前,我们需要声明并对其进行初始化(分配值)。与 JavaScript 不同,在 CoffeeScript 中创建变量时,不需要使用 var 关键字来声明它。正如您在下面看到的那样,我们只需给文字值赋值即可创建变量。

In JavaScript, before using a variable, we need to declare and initialize it (assign value). Unlike JavaScript, while creating a variable in CoffeeScript, there is no need to declare it using the var keyword. We simply create a variable just by assigning a value to a literal as shown below.

name = variable name

Example

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

In the following CoffeeScript code, we have defined two variables name and age, of string and number data types respectively. Save it in a file with the name variable_example.coffee.

name = "Javed"
age = 25

Compiling the code

Compiling the code

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

Compile the above CoffeeScript code by executing the following command in the command prompt.

c:\> compile -c variable_example.coffee

编译后,将生成一个名为 variable_example.js 的 JavaScript 文件,内容如下。在这里,您可以观察到编译器使用 var 关键字替我们声明了变量(age 和 name)。

On compiling, a JavaScript file named variable_example.js will be generated with the following content. Here you can observe that the compiler declared the variables (age and name) using the var keyword on behalf of us.

// Generated by CoffeeScript 1.10.0
(function() {
  var age, name;
  name = "Javed";
  age = 25;

}).call(this);

Variable Scope

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

The scope of a variable is the region of your program in which it is defined. JavaScript and CoffeeScript variables have only two scopes.

  1. Global Variables − A global variable has global scope which means it can be used anywhere in your JavaScript code.

  2. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

The Problem with Variables in JavaScript

在 JavaScript 中,每当我们在不使用 var 关键字的情况下定义变量时,它就会以全局作用域创建。这会导致许多问题。请考虑以下示例 −

In JavaScript, whenever we define a variable without using the var keyword, it is created with global scope. This causes a lot of problems. Consider the following example −

<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 代码会给您以下输出 −

On executing, the above JavaScript gives you the following output −

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。

In the above example, we have created a variable named i in the global space and assigned the value 10 to it. And within the function, on an attempt to create a local variable with the same name, we have declared as i=20; without var keyword. Since we missed the var keyword, the value of global variable i is reassigned to 20.

出于这个原因,建议使用 var 关键字声明变量。

For this reason, it is recommended to declare variables using the var keyword.

Variable Scope in CoffeeScript

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

Whenever we compile a CoffeeScript file, the CoffeeScript compiler creates an anonymous function, and within that function, it transcompiles the CoffeeScript code in to JavaScript line by line. (If we want, we can remove the top level function wrapper using the -b or --bare option of the compile command) Every variable that we create is declared using the var keyword within the anonymous function and thus, by default, every variable is local in CoffeeScript.

(function() {
  var age, name;
  name = "javed";
  age = 20;
}).call(this);

无论如何,如果我们愿意,我们可以声明一个具有全局名称空间的变量。我们可以像下面显示的那样显式地进行此操作。

Anyway, if we want, we can declare a variable with global namespace. We can do it explicitly as shown below.

obj = this
obj.age = 30

CoffeeScript Variable Names (Literals)

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

While naming your variables in CoffeeScript, keep the following rules in mind.

  1. You should not use any of the CoffeeScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or Boolean variable names are not valid.

  2. CoffeeScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.

  3. CoffeeScript variable names are case-sensitive. For example, Name and name are two different variables.

CoffeeScript - Operators and Aliases

CoffeeScript Operators

运算符是一个符号,告诉编译器执行特定的数学或逻辑函数。让我们来看一个简单的表达式 4 + 5 is equal to 9 。此处 4 和 5 称为 operands ,而 “+” 称为 operator

An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called the operator.

CoffeeScript 提供的运算符与 JavaScript 中的运算符相同,但有一些区别。在 JavaScript 中有一些有问题的运算符。CoffeeScript 或者移除了它们,或者修改了它们的功能,并且还引入了一些新的运算符。

The operators provided by CoffeeScript are same as in JavaScript except a few differences. There are some problematic operators in JavaScript. CoffeeScript either removed them or modified their functionality and it also introduced some new operators.

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

Following is the list of operators supported by CoffeeScript.

  1. Arithmetic Operators

  2. Comparison Operators

  3. Logical (or Relational) Operators

  4. Assignment Operators

CoffeeScript Aliases

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

In addition to operators, CoffeeScript also provides aliases. CoffeeScript provides aliases to various operators and symbols in order to make your CoffeeScript code readable and more user friendly.

让我们逐个了解 CoffeeScript 的所有运算符和别名。

Let us have a look at all the operators and aliases of CoffeeScript one by one.

Arithmetic Operators

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

CoffeeScript supports the following arithmetic operators. Assume variable A holds 10 and variable B holds 20, then −

S.No

Operator and Description

Example

1

+ (Addition) Adds two operands

A + B = 30

2

− (Subtraction) Subtracts the second operand from the first

A - B = -10

3

* (Multiplication) Multiply both operands

A * B = 200

4

/ (Division) Divide the numerator by the denominator

B / A = 2

5

% (Modulus) Outputs the remainder of an integer division

B % A = 0

6

++ (Increment) Increases an integer value by one

A++ = 11

7

-- (Decrement) Decreases an integer value by one

A-- = 9

Comparison Operators

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

JavaScript supports the following comparison operators. Assume variable A holds 10 and variable B holds 20, then −

S.No

Operator and Description

Example

1

= = (Equal) Checks if the value of two operands are equal or not, if yes, then the condition becomes true.

(A == B) is not true.

2

!= (Not Equal) Checks if the value of two operands are equal or not, if the values are not equal, then the condition becomes true.

(A != B) is true.

3

> (Greater than) Checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition becomes true.

(A > B) is not true.

4

< (Less than) Checks if the value of the left operand is less than the value of the right operand, if yes, then the condition becomes true.

(A < B) is true.

5

>= (Greater than or Equal to) Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition becomes true.

(A >= B) is not true.

6

⇐ (Less than or Equal to) Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition becomes true.

(A ⇐ B) is true.

下表显示了少数比较运算符的别名。假设 A 作用 20 ,变量 B 作用 20

Following table shows the aliases for few of the Comparison operators. Suppose A holds 20 and variable B holds 20.

Operator

Alias

Example

= = (Equal)

is

A is B gives you true.

!= = (Not Equal)

isnt

A isnt B gives you false.

Logical Operators

CoffeeScript 支持以下逻辑运算符。假设变量 A 作用 10 ,变量 B 作用 20 ,那么 −

CoffeeScript supports the following logical operators. Assume variable A holds 10 and variable B holds 20, then −

S.No

Operator and Description

Example

1

&& (Logical AND) If both the operands are non-zero, then the condition becomes true.

(A && B) is true.

2

*

(Logical OR)* If any of the two operands are non-zero, then the condition becomes true.

(A

B) is true.

3

! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false.

下表显示了少数逻辑运算符的别名。假设 X 作用 true ,变量 Y 作用 false

The following table shows the aliases for some of the logical operators. Suppose X holds true and variable Y holds false.

Operator

Alias

Example

&& (Logical AND)

and

X and Y gives you false

(Logical OR)

or

X or Y gives you true

! (not x)

Bitwise Operators

CoffeeScript 支持以下逐位运算符。假设变量 A 作用 2 ,变量 B 作用 3 ,那么 −

CoffeeScript supports the following bitwise operators. Assume variable A holds 2 and variable B holds 3, then −

S.No

Operator and Description

Example

1

& (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments.

(A & B) is 2.

2

*

(BitWise OR)* It performs a Boolean OR operation on each bit of its integer arguments.

(A

B) is 3.

3

^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.

(A ^ B) is 1.

4

~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand.

(~B) is -4.

5

<< (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on.

(A << 1) is 4.

6

Assignment Operators

Coffeescript 支持以下赋值运算符 -

CoffeeScript supports the following assignment operators −

S.No

Operator and Description

Example

1

= (Simple Assignment ) Assigns values from the right side operand to the left side operand

C = A + B will assign the value of A + B into C

2

+= (Add and Assignment) It adds the right operand to the left operand and assigns the result to the left operand.

C += A is equivalent to C = C + A

3

-= (Subtract and Assignment) It subtracts the right operand from the left operand and assigns the result to the left operand.

C -= A is equivalent to C = C - A

4

*= (Multiply and Assignment) It multiplies the right operand with the left operand and assigns the result to the left operand.

C *= A is equivalent to C = C * A

5

/= (Divide and Assignment) It divides the left operand with the right operand and assigns the result to the left operand.

C /= A is equivalent to C = C / A

6

%= (Modules and Assignment) It takes modulus using two operands and assigns the result to the left operand.

C %= A is equivalent to C = C % A

Note − 同样的逻辑适用于按位运算符,所以它们将变成 <⇐, >>=, >>=, &=, |= 和 ^=.

Note − Same logic applies to Bitwise operators so they will become like <⇐, >>=, >>=, &=, |= and ^=.

Equality Operator in CoffeeScript

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

While working with JavaScript, you will encounter two types of equality operators == and ===.

JavaScript 中的 == 运算符为 type coercive ,即如果运算中两个操作数的类型不同,则一个操作数的数据类型将被转换为另一个并进行比较。

The == operator in JavaScript is type coercive, i.e., if the types of the two operands in an operation are different, then the data type of one of the operator is converted into other and then both are compared.

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

CoffeeScript avoids this undesirable coercion, it compiles the == operator in to the strict comparison operator of JavaScript ===.

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

If we compare two operands using ===, then it returns true, only if both the value and datatypes of them are equal, else it returns false.

Example

考虑以下示例。这里我们有两个变量 aba 持有整数类型的值 21, b 持有相同的值,但它属于 string 类型。在 CoffeeScript 中,当我们比较 ab 时,结果将为 false 。(由于 CoffeeScript 的 == 操作符被转换为 JavaScript 的 === 操作符)

Consider the following example. Here we have two variables a and b. a holds the value 21 of integer type and b holds the same value, but it is of string type. In CoffeeScript, when we compare a and b, the result will be false. (Since the == operator of CoffeeScript is converted to === operator of JavaScript)

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

编译时,上述 CoffeeScript 产生以下 JavaScript

On compiling, the above CoffeeScript produces the following JavaScript

// Generated by CoffeeScript 1.10.0
(function() {
  var a, b, result;

  a = 21;

  b = "21";

  result = a === b;
  console.log(result);
}).call(this);

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

On executing, it produces the following output.

false

The existential Operator

CoffeeScript 提供了一个称为存在操作符的新操作符来验证变量的存在。它由 ? 表示。除非变量为 null 或 undefined,否则存在操作符返回真。

CoffeeScript provides a new operator known as existential operator to verify the existence of a variable. It is denoted by ?. Unless a variable is null or undefined, the existential operator returns true.

Example

下面给出了存在操作符的一个示例。这里我们有三个变量,即 name, agesubject ,我们正在使用存在操作符来验证变量 name 和 phone 的存在。

Given below is an example of the existential operator. Here we have three variables, namely name, age, and subject and we are verifying the existence of the variables name and phone using existential operator.

name="Ramu"
age=24
subject="Engineering"
verify_name = name?
verify_phone = phone?
console.log verify_name
console.log verify_phone

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

On compiling, this will generate the following JavaScript code.

// 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 文件,它将产生以下输出。

If we execute the above CoffeeScript file, it produces the following output.

true
false

Note − 我们有存在操作符的访问器变体 ? 。我们可以使用它来代替 . 操作符来找出空引用。

Note − We have an accessor variant of the existential operator ?. We can use it instead of the . operator to find out the null references.

Chained Comparisons

像在 Python 中一样,我们可以在 CoffeeScript 中的单个表达式中使用一连串比较操作符。

As in Python, we can use a chain of comparison operators in a single expression in CoffeeScript.

Example

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

Following is an example of using chained comparison.

score = 70
passed = 100 > score > 40

console.log passed

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

On compiling, the example CoffeeScript gives you the following JavaScript code.

// Generated by CoffeeScript 1.10.0
(function() {
  var passed, score;

  score = 70;

  passed = (100 > score && score > 40);

  console.log(passed);

}).call(this);

如果您执行上述 CoffeeScript 代码,它将产生以下输出。

If you execute the above CoffeeScript code, it produces the following output.

true

Note − CoffeeScript 移除了三元操作符;相反,我们可以使用 inline if 语句。

Note − CoffeeScript removes the ternary operator; instead of it, we can use the inline if statement.

CoffeeScript Aliases

通常,CoffeeScript 为各种操作符和符号提供别名,以使您的 CoffeeScript 代码可读且更易于用户使用。以下是 CoffeeScript 提供的别名。

In general, CoffeeScript provides aliases to various operators and symbols in order to make your CoffeeScript code readable and more user friendly. Following are the aliases provided by CoffeeScript.

Name

Operator / symbol

Aliases

"equals to" operator

==

is

"not equals to" operator

!==

isnt

"not" operator

!

not

"and" operator

&&

and

"or" operator

or

boolean value true

true

true, yes, on

boolean value false

false

off, no

current object

this

@

new line (or) semi colon

\n or ;

then

Inverse of if

! if

unless

To test for array presence

in

To test for object presence

of

Exponentiation

a****b

Integer division

a*//*b

dividend dependent modulo

Example

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

The following example shows how to use aliases in 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 代码。

On compiling the above example, it gives you the following JavaScript code.

// 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 文件,它会生成以下输出 −

If you execute the above CoffeeScript file, it produces the following output −

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

CoffeeScript - Conditionals

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

While programming, we encounter some scenarios where we have to choose a path from a given set of paths. In such situations, we need conditional statements. Conditional statements help us take decisions and perform right actions.

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

Following is the general form of a typical decision-making structure found in most of the programming languages.

decision making structure

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

JavaScript supports the if statement (including its variants) and switch statement. In addition to the conditionals available in JavaScript, CoffeeScript includes the unless statement, the negation of if, and even more.

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

Following are the conditional statements provided by CoffeeScript.

S.No.

Statement & Description

1

if statementAn if statement consists of a Boolean expression followed by one or more statements. These statements execute when the given Boolean expression is true.

2

if…​else statementAn if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

3

unless statementAn unless statement is similar to if with a Boolean expression followed by one or more statements except. These statements execute when a given Boolean expression is false.

4

unless…​else statementAn unless statement can be followed by an optional else statement, which executes when a Boolean expression is true.

5

switch statementA switch statement allows a variable to be tested for equality against a list of values.

The then Keyword in CoffeeScript

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

The if and unless statements are block statements that are written in multiple lines. CoffeeScript provides the then keyword using which we can write the if and the unless statements in a single line.

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

Following are the statements in CoffeeScript that are written using then keyword.

S.No.

Statement & Description

1

if-then statementUsing the if-then statement we can write the if statement of CoffeeScript in a single line. It consists of a Boolean expression followed by then keyword, which is followed by one or more statements. These statements execute when the given Boolean expression is true.

2

if-then…​else statementThe if-then statement can be followed by an optional else statement, which executes when the Boolean expression is false. Using if-then…​else statement, we can write the if…​else statement in a single line.

3

unless-then statementUsing the unless-then statement, we can write the unless statement of CoffeeScript in a single line. It consists of a Boolean expression followed by then keyword, which is followed by one or more statements. These statements execute when the given Boolean expression is false.

4

unless…​then else statementThe unless-then statement can be followed by an optional else statement, which executes when the Boolean expression is true. Using unless-then…​else statement, we can write the unless…​else statement in a single line.

postfix if and postfix unless Statements

在 CoffeeScript 中,你还可以编写 ifunless 语句,首先有一个代码块,然后是 ifunless 关键字,如下所示。这是这些语句的后缀形式。在用 CoffeeScript 编写程序时,非常方便。

In CoffeeScript, you can also write the if and unless statements having a code block first followed by if or unless keyword as shown below. This is the postfix form of those statements. It comes handy while writing programs in CoffeeScript.

#Postfix if
Statements to be executed if expression

#Postfix unless
Statements to be executed unless expression

CoffeeScript - Loops

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

While coding, you may encounter a situation where you need to execute a block of code over and over again. In such situations, you can use loop statements.

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

In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

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

A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages

loop architecture

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

JavaScript provides while, for and for..in loops. The loops in CoffeeScript are similar to those in JavaScript.

while 循环及其变体是 CoffeeScript 中唯一的循环构造。CoffeeScript 没有采用常用的 for 循环,而是为您提供了 Comprehensions ,这些内容将在后面的章节中详细讨论。

while loop and its variants are the only loop constructs in CoffeeScript. Instead of the commonly used for loop, CoffeeScript provides you Comprehensions which are discussed in detail in later chapters.

The while loop in CoffeeScript

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

The while loop is the only low-level loop that CoffeeScript provides. It contains a Boolean expression and a block of statements. The while loop executes the specified block of statements repeatedly as long as the given Boolean expression is true. Once the expression becomes false, the loop terminates.

Syntax

以下是在 CoffeeScript 中 while 循环的语法。在此处,无需使用圆括号来指定布尔表达式,并且我们必须使用(一致数量的)空格缩进循环主体,而不是用大括号将其括起来。

Following is the syntax of the while loop in CoffeeScript. Here, there is no need of the parenthesis to specify the Boolean expression and we have to indent the body of the loop using (consistent number of) whitespaces instead of wrapping it with curly braces.

while expression
   statements to be executed

Example

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

The following example demonstrates the usage of while loop in CoffeeScript. Save this code in a file with name 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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c while_loop_example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee while_loop_example.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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

Variants of while

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

The While loop in CoffeeScript have two variants namely the until variant and the loop variant.

S.No.

Loop Type & Description

1

until variant of whileThe until variant of the while loop contains a Boolean expression and a block of code. The code block of this loop is executed as long as the given Boolean expression is false.

2

loop variant of whileThe loop variant is equivalent to the while loop with true value (while true). The statements in this loop will be executed repeatedly until we exit the loop using the Break statement.

CoffeeScript - Comprehensions

在上一个章节中,我们了解了 CoffeeScript 提供的各种循环、 while 及其变体。除此之外,CoffeeScript 还提供了称为 comprehensions 的附加循环结构。

In the previous chapter, we have learnt various loops provided by CoffeeScript, while and its variants. In addition to those, CoffeeScript provides additional loop structures known as comprehensions.

如果我们添加可选的保护子句和当前数组索引的值,这些列表解析会替换其他编程语言中的 for 循环。使用列表解析,我们可以遍历数组和对象,而遍历数组的列表解析是表达式,而且我们可以在函数中返回它们或将它们分配给变量。

These comprehensions replace the for loop in other programming languages, if we add the optional guard clauses and the value of the current array index explicitly. Using comprehensions, we can iterate arrays as well as objects and the comprehensions that iterate arrays are expressions, and we can return them in a function or assign to a variable.

S.No.

Statement & Description

1

for..in comprehensionsThe for..in comprehension is the basic form of comprehension in CoffeeScript using this we can iterate the elements of a list or array.

2

for..of comprehensionsJust like Arrays CoffeeScriptScript provides a containers to store key-value pairs known as objects. We can iterate objects using the for..of comprehensions provided by CoffeeScript.

3

list comprehensionsThe list comprehensions in CoffeeScript are used to map an array of objects to another array.

Index of comprehensions

元素列表/数组有一个索引,可以在列表解析中使用。您可以使用变量在列表解析中使用它,如下所示:

The list/array of elements have an index which can be used in comprehensions. You can use it in comprehensions using a variable as shown below.

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

Example

以下示例演示了在 CoffeeScript 中使用 for…in 理解的索引。将以下代码保存在一个名叫 for_in_index.coffee 的文件中

The following example demonstrates the usage of index of the for…in comprehension in CoffeeScript. Save this code in a file with name 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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c for_in_index.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee for_in_index.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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 form of comprehensions

与后缀 ifunless 类似,CoffeeScript 提供了理解的后缀形式,在编写代码时非常方便。使用此功能,我们可以在单行中编写 for..in 理解,如下所示。

Just like postfix if and unless, CoffeeScript provides the postfix form of the Comprehensions which comes handy while writing the code. Using this, we can write the for..in comprehension in a single line as shown below.

#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}

Assigning to a variable

我们用于遍历数组的理解可以赋值给变量,也可以由函数返回。

The comprehension we use to iterate arrays can be assigned to a variable and also returned by a function.

Example

考虑以下示例。在这里,您可以观察到我们使用 for..in 理解检索了数组的元素,并将其赋给名为 names 的变量。我们还拥有一个函数,该函数使用 return 关键字明确返回理解。将以下代码保存在一个名叫 example.coffee 的文件中

Consider the example given below. Here you can observe that we have retrieved the elements of an array using for..in comprehension and assigned this to a variable named names. And we also have a function which returns a comprehension explicitly using the return keyword. Save this code in a file with name 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 names 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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee example.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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

The by keyword

CoffeeScript 提供范围来定义元素列表。例如,范围 [1..10] 等同于 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],其中的每个元素都会增加 1。我们还可以使用理解的 by 关键字更改此增量。

CoffeeScript provides ranges to define a list of elements. For example, the range [1..10] is equivalent to [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] where, every element is incremented by 1. We can also change this increment using the by keyword of comprehensions.

Example

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

The following example demonstrates the usage of the by keyword of the for..in comprehension provided by CoffeeScript. Save this code in a file with name by_keyword_example.coffee

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

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c by_keyword_example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee by_keyword_example.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

[ 1, 3, 5, 7, 9 ]

CoffeeScript - Functions

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

A function is a block of reusable code that can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes.

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

Functions allow a programmer to divide a big program into a number of small and manageable functions.

通常,使用 JavaScript,我们可以定义两种类型的函数 – named functions ,具有函数名称主体的常规函数, Function expressions 。使用函数表达式,我们可以将函数分配给变量。

In general, using JavaScript, we can define two types of functions – named functions, the regular functions with function name body and, Function expressions. Using function expressions, we can assign functions to variables.

//named function
function sayHello(){
   return("Hello there");
}

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

Functions in CoffeeScript

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

The syntax of function in CoffeeScript is simpler as compared to JavaScript. In CoffeeScript, we define only function expressions.

function 关键字在 CoffeeScript 中被取消。若要在此处定义一个函数,我们必须使用一个瘦箭头 ( )。

The function keyword is eliminated in CoffeeScript. To define a function here, we have to use a thin arrow ().

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

Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below.

(function() {});

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

It is not mandatory to use the return keyword in CoffeeScript. Every function in CoffeeScript returns the last statement in the function automatically.

  1. If we want to return to the calling function or return a value before we reach the end of the function, then we can use the return keyword.

  2. In addition to in-line functions (functions that are in single line), we can also define multiline functions in CoffeeScript. Since the curly braces are eliminated, we can do it by maintaining proper indentations.

Defining a Function

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

Following is the syntax of defining a function in CoffeeScript.

function_name = -> function_body

Example

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

Given below is an example of a function in CoffeeScript. In here, we have created a function named greet. This function automatically returns the statement in it. Save it in a file with the name function_example.coffee

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

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

Compile it by executing the following command in the command prompt.

c:\>coffee -c function_example.coffee

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

On compiling, it generates the following JavaScript code. Here you can observe that the CoffeeScript compiler automatically returned the string value in the function named greet().

// Generated by CoffeeScript 1.10.0
(function() {
  var greet;

  greet = function() {
    return "This is an example of a function";
  };

}).call(this);

Multi-line Functions

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

We can also define a function with multiple lines by maintaining indentations instead of curly braces. But we have to be consistent with the indentation we follow for a line throughout a function.

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

在编译时,以上 CoffeeScript 为你提供了以下 JavaScript 代码。CoffeeScript 编译器获取了我们使用缩进来分隔且置于大括号内的函数主体。

On compiling, the above CoffeeScript gives you the following JavaScript code. The CoffeeScript compiler grabs the body of the function that we have separated using indentations and placed within the curly braces.

// Generated by CoffeeScript 1.10.0
(function() {
  var greet;

  greet = function() {
    return console.log("Hello how are you");
  };

}).call(this);

Functions with Arguments

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

We can also specify arguments in a function using parenthesis as shown below.

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

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

On compiling the above CoffeeScript file, it will generate the following 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);

Invoking a Function

定义一个函数之后,我们需要调用该函数。你只需在函数名后加上圆括号即可调用函数,如以下示例所示。

After defining a function, we need to invoke that function. You can simply invoke a function by placing parenthesis after its name as shown in the following example.

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

在编译时,上述示例会生成以下 JavaScript

On compiling, the above example gives you the following 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 代码时,会生成以下输出。

On executing the above CoffeeScript code, it generates the following output.

Sum of the two numbers is: 50

Invoking Functions with Arguments

同样地,我们可以通过向函数传递参数来调用它,如下所示。

In the same way, we can invoke a function with arguments by passing them to it as shown below.

my_function argument_1,argument_2
or
my_function (argument_1,argument_2)

Note − 在通过向函数传递参数来调用函数时,使用圆括号是可选的。

Note − While invoking a function by passing arguments to it, the usage of parenthesis is optional.

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

In the following example, we have created a function named add() that accepts two parameters and we have invoked it.

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

在编译时,上述示例会生成以下 JavaScript。

On compiling, the above example gives you the following 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 代码会生成以下输出。

On executing, the above CoffeeScript code it generates the following output.

Sum of the two numbers is: 30

Default Arguments

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

CoffeeScript supports default arguments too. We can assign default values to the arguments of a function, as shown in the following example.

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 文件。

On compiling, the above CoffeeScript generates the following JavaScript file.

// 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 代码时,会生成以下输出。

On executing the above CoffeeScript code, it generates the following output.

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

CoffeeScript - Strings

String 对象允许你使用一系列字符。在大多数编程语言中,在 CoffeeScript 中字符串使用引号声明,如下所示:−

The String object lets you work with a series of characters. As in most of the programming languages, the Strings in CoffeeScript are declared using quotes as −

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

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

On compiling, it will generate the following JavaScript code.

// Generated by CoffeeScript 1.10.0
(function() {
  var my_string;

  my_string = "Hello how are you";

  console.log(my_string);

}).call(this);

String Concatenation

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

We can concatenate two strings using the "+" symbol as shown below.

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

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

On compiling, it will generate the following JavaScript code.

// Generated by CoffeeScript 1.10.0
(function() {
  var new_string;

  new_string = "Hello how are you " + "Welcome to Tutorialspoint";

  console.log(new_String);

}).call(this);

如果你执行上述示例,你可以观察到连接后的字符串,如下所示。

If you execute the above example, you can observe the concatenated String as shown below.

Hello how are you Welcome to Tutorialspoint

String Interpolation

CoffeeScript 还提供一个称为 String interpolation 的功能,用于在字符串中包含变量。CoffeeScript 的该功能受 Ruby 语言启发。

CoffeeScript also provides a feature known as String interpolation to include variables in stings. This feature of CoffeeScript was inspired from Ruby language.

字符串内插使用双引号 "" 、一个井号 # 和一对花括号 { } 完成。字符串在双引号中声明,要内插的变量包装在花括号中,花括号之前加上井号,如下所示。

String interpolation was done using the double quotes "", a hash tag # and a pair of curly braces { }. The String is declared in double quotes and the variable that is to be interpolated is wrapped within the curly braces which are prefixed by a hash tag as shown below.

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

在编译上述示例时,它会生成以下 JavaScript。此处你可以观察到,字符串内插使用 + 符号转换为正常的连接。

On compiling the above example, it generates the following JavaScript. Here you can observe the String interpolation is converted into normal concatenation using the + symbol.

// Generated by CoffeeScript 1.10.0
(function() {
  var age, message, name;

  name = "Raju";

  age = 26;

  message = "Hello " + name + " your age is " + age;

  console.log(message);

}).call(this);

如果你执行上述 CoffeeScript 代码,它会给你以下输出。

If you execute the above CoffeeScript code, it gives you the following output.

Hello Raju your age is 26

只有当字符串用双引号 " " 括起来时,才会内插作为 #{variable} 传递的变量。使用单引号 ' ' (而不是双引号)会产生没有内插的文本行。请考虑以下示例。

The variable that is passed as #{variable} is interpolated only if the string is enclosed between double quotes " ". Using single quotes ' ' instead of double quotes produces the line as it is without interpolation. Consider the following example.

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

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

If we use single quotes instead of double quotes in interpolation, you will get the following output.

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

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

CoffeeScript allows multiple lines in Strings without concatenating them as shown below.

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

它生成以下输出。

It generates the following output.

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

JavaScript String Object

JavaScript 的 String 对象允许你处理一系列字符。此对象提供给你许多方法,可在字符串上执行各种操作。

The String object of JavaScript lets you work with a series of characters. This object provides you a lot of methods to perform various operations on Stings.

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

Since we can use JavaScript libraries in our CoffeeScript code, we can use all those methods in our CoffeeScript programs.

String Methods

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

Following is the list of methods of the String object of JavaScript. Click on the name of these methods to get an example demonstrating their usage in CoffeeScript.

S.No.

Method & Description

1

charAt()Returns the character at the specified index.

2

charCodeAt()Returns a number indicating the Unicode value of the character at the given index.

3

concat()Combines the text of two strings and returns a new string.

4

indexOf()Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.

5

lastIndexOf()Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.

6

localeCompare()Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

7

match()Used to match a regular expression against a string.

8

search()Executes the search for a match between a regular expression and a specified string.

9

slice()Extracts a section of a string and returns a new string.

10

split()Splits a String object into an array of strings by separating the string into substrings.

11

substr()Returns the characters in a string beginning at the specified location through the specified number of characters.

12

toLocaleLowerCase()The characters within a string are converted to lower case while respecting the current locale.

13

toLocaleUpperCase()The characters within a string are converted to upper case while respecting the current locale.

14

toLowerCase()Returns the calling string value converted to lower case.

15

toUpperCase()Returns the calling string value converted to uppercase.

CoffeeScript - Arrays

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

The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Syntax

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

To create an array, we have to instantiate it using the new operator as shown below.

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

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

The Array() constructor accepts the list of string or integer types. We can also specify the length of the array by passing a single integer to its constructor.

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

We can also define an array by simply providing the list of its elements in the square braces ([ ]) as shown below.

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

Example

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

Following is an example of defining an array in CoffeeScript. Save this code in a file with name array_example.coffee

student = ["Rahman","Ramu","Ravi","Robert"]

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c array_example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var student;

  student = ["Rahman", "Ramu", "Ravi", "Robert"];

}).call(this);

New line instead of comma

我们还可以通过在每一行中创建新元素并保持适当缩进来删除数组元素之间的逗号 (,),如下所示。

We can also remove the comma (,) between the elements of an array by creating each element in a new line by maintaining proper indentation as shown below.

student = [
  "Rahman"
  "Ramu"
  "Ravi"
  "Robert"
  ]

Comprehensions over arrays

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

We can retrieve the values of an array using comprehensions.

Example

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

The following example demonstrates the retrieval of elements of an array using comprehensions. Save this code in a file with name array_comprehensions.coffee

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

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c array_comprehensions.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee array_comprehensions.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

Rahman
Ramu
Ravi
Robert

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

Unlike the Arrays in other programming languages the arrays in CoffeeScript can have multiple types of data i.e. both string and numericals.

Example

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

Here is an example of a CoffeeScript array holding multiple types of data.

students = [ "Rahman", "Ramu", "Ravi", "Robert",21 ]

CoffeeScript - Objects

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

Objects in CoffeeScript are similar to those in JavaScript. These are a collection of the properties, where a property includes a key and a value separated by a semi colon (;). In short, CoffeeScript objects are a collection of key-value pairs. The objects are defined using curly braces, an empty object is represented as {}.

Syntax

以下是 CoffeeScript 中对象的语法。在此处,我们将对象的键值对放在大括号中,并使用逗号将其分隔( , )。

Given below is the syntax of an object in CoffeeScript. In here, we place the key-value pairs of the objects within the curly braces and they are separated using comma (,).

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

Example

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

Following is an example of defining an object in CoffeeScript. Save this code in a file with name objects_example.coffee

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

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

> coffee -c objects_example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var student;

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

}).call(this);

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

Just as in arrays, we can remove the commas by specifying the key-value pairs in new lines as shown below.

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

Indentations instead of curly braces

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

Just like other block statements in CoffeeScript, we can use indentations instead of curly braces {} as shown in the following example.

Example

我们可以将上述示例重写为没有大括号,如下所示。

We can rewrite the above example without curly braces as shown below.

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

Nested objects

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

In CoffeeScript, we can write objects within objects.

Example

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

The following example demonstrates the nested objects in CoffeeScript. Save this code in a file with name nested_objects.coffee

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

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

> coffee -c nested_objects.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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);

Comprehensions over objects

我们可以使用列表解析来遍历对象的元素。遍历对象元素与遍历数组元素相同。在对象中,我们需要检索 key 和值这两个元素,因此我们会使用两个变量。

To iterate over the contents of an object, we can use comprehensions. Iterating the contents of an object is same as iterating the contents of an array. In objects, since we have to retrive two elements keys and values we will use two variables.

Example

以下示例演示了如何使用列表解析来遍历对象元素。将以下代码保存至一个名为 object_comprehensions.coffee 的文件中:

The following is an example showing how to iterate the contents of an object using comprehensions. Save this code in a file with name object_comprehensions.coffee

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

console.log key+"::"+value for key,value of student

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

> coffee -c object_comprehensions.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

> coffee object_comprehensions.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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

Arrays of Objects

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

In CoffeeScript, an array can also contain objects in as shown below.

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

以下示例演示如何定义一个对象数组。我们可以仅列出所需对象的关键值对,并使用逗号将其分隔 (,)

The following example shows how to define an array of objects. We can just list the key value pairs of the objects we want in an array by separating them using commas (,).

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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c array_of_objects.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee array_of_objects.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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

Reserved Keywords

JavaScript 不允许将保留关键字用作对象的属性名,如果我们希望使用它们,则需要使用双引号将其包装起来 " "

JavaScript does not allow reserved keywords as property names of an object, if we want use them, we have to wrap them using double quotes " ".

Example

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

Consider the following example. Here we have created a property with name class, which is a reserved keyword. Save this code in a file with name reserved_keywords.coffee

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

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c reserved_keywords.coffee

在编译时,它会给您以下 JavaScript。您可以在此处观察到,CoffeeScript 编译器已代表我们使用双引号包装了关键字 class。

On compiling, it gives you the following JavaScript. Here you can observe that the CoffeeScript compiler wrapped the keyword class with double quotes on behalf of us.

// Generated by CoffeeScript 1.10.0
(function() {
  var key, student, value;

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

  for (key in student) {
    value = student[key];
    console.log(key + "::" + value);
  }

}).call(this);

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

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee array_of_objects.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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

CoffeeScript - Ranges

在上一章中,我们已经看到了 CoffeeScript 中的数组,而在编程过程中,我们会面临一些场景其中,我们必须将一系列数值存储在一个数组中,如下所示。

In the previous chapter, we have seen Arrays in CoffeeScript, while programming we will face some scenarios where we have to store a sequence of numerical values in an array as shown below.

numbers =[1,2,3,4,5,6,7,8,9,10]

CoffeeScript 提供了一种更简洁的方法来表达包含一系列数值的数组,即 ranges 。CoffeeScript 的此功能源自 Ruby。

CoffeeScript provides a shorter way of expressing the arrays containing a sequence of numerical values, known as ranges. This feature of CoffeeScript is inspired from Ruby.

Syntax

范围由两个数值创建,范围中的第一个和最后一个位置,它们由 .. 或 …​ 分隔。使用两个点(1..4),范围是包含(1、2、3、4);使用三个点(1…​4),范围不包括结尾(1、2、3)。

Ranges are created by two numerical values, the first and last positions in the range, separated by .. or …​. With two dots (1..4), the range is inclusive (1, 2, 3, 4); with three dots (1…​4), the range excludes the end (1, 2, 3).

下面给出 CoffeeScript 中范围的语法。我们将 square braces [ ] 中的范围内的数值定义,就像数组一样。在范围内,在存储一系列数值时,我们不必提供整个序列的值,我们只要按照下面所示,用两个点 .. 分隔其 beginend 值即可。

Given below is the syntax of ranges in CoffeeScript. We will define the values in a range between square braces [ ] just like arrays. In ranges, while storing a sequence of numerical values, instead of providing the values of the whole sequence, we can just specify its begin and end values separated by two dots (..) as shown below.

range =[Begin..End]

Example

以下是 CoffeeScript 中范围的示例。将此内容保存到名为 ranges_example.coffee 的文件中。

Here is an example of ranges in CoffeeScript. Save this in a file with name ranges_example.coffee.

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

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c ranges_example.coffee

在编译过程中,它会提供以下 JavaScript。在这里,你可以观察范围被转换为完整的 CoffeeScript 数组。

On compiling, it gives you the following JavaScript. Here you can observe that the range is converted in to complete CoffeeScript array.

// Generated by CoffeeScript 1.10.0
(function() {
  var numbers;

  numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

  console.log("The contents of the range are:: " + numbers);

}).call(this);

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

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee ranges_example.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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

Excluding the end Value

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

The ranges are compiled into complete arrays containing all numbers. If we want to exclude the end value, then we have to separate the start and end elements of the range using three dots (…​) as shown below.

range =[Begin...End]

Example

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

We can rewrite the above example by excluding the end value as shown below. Save the following contents in a file with name range_excluding_end.coffee

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

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c ranges_example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee ranges_example.coffee

在执行时,CoffeeScript 文件会产生以下输出。在这里,你可以观察到结尾值 9 被排除在外。

On executing, the CoffeeScript file produces the following output. In here, you can observe that the end value 9 is excluded.

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

Using Ranges with Variables

我们还可以通过将 start 和 end 值赋值给变量来定义范围。

We can also define a range by assigning the start and end values to variables.

Example

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

Consider the following example. Here we have defined a range using variables. Save this code in a file with name range_variables.coffee

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

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c range_variables.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee range_variables.coffee

在执行时,CoffeeScript 文件会产生以下输出。在这里,你可以观察到结尾值 9 被排除在外。

On executing, the CoffeeScript file produces the following output. In here, you can observe that the end value 9 is excluded.

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

Ranges with Arrays

我们可以通过将其与范围结合使用来分割数组。每当我们在数组(变量)之后立即指定范围时,CoffeeScript 编译器会将其转换为 JavaScript 的 slice() 方法调用。

We can slice arrays by using them with ranges. Whenever we specify ranges immediately after arrays (variables), then the CoffeeScript compiler converts it in to a slice() method call of JavaScript.

假设我们有一个包含数值的数组(0 到 9),那么我们可以像下面这样检索它的前 4 个元素。

Assume that we have an array having numerical values, say 0 to 9, then we can retrieve the first 4 elements of it as shown below.

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

负值表示从后往前数的元素数量,例如,-1 表示 9。如果我们指定一个负数 3 后面跟着两个冒号,则将提取该数组的最后三个元素。

Negative values represent the elements from the end, for example, -1 indicates 9. If we specify a negative number 3 followed by two dots, the last three elements of the array will be extracted.

data = num[-3..]

如果我们只指定数组范围中两个冒号 num[..] ,则将提取完整数组。我们还可以使用范围替换数组片段,如下所示。

If we specify only two dots in the range of an array as num[..], then the complete array will be extracted. We can also replace an array segment with other elements using ranges as shown below.

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

Example

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

The following example demonstrates the use of ranges with arrays. Save this code in a file with name 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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c range_arrays.coffee

编译后,它会输出以下 JavaScript。在这里,你可以看到所有范围都转换为 JavaScript 的 slice() 方法调用。

On compiling, it gives you the following JavaScript. Here you can observe that all the ranges are converted in to the slice() method calls of JavaScript.

// 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee range_arrays.coffee

在执行时,CoffeeScript 文件会产生以下输出。在这里,你可以观察到结尾值 9 被排除在外。

On executing, the CoffeeScript file produces the following output. In here, you can observe that the end value 9 is excluded.

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

Ranges with Strings

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

We can also use ranges with Strings. If we specify ranges after Strings, then CoffeeScript slices them and returns a new subset of characters.

Example

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

The following example demonstrates the use of ranges with Strings. Here we have created a string and extracted a substring from it using ranges. Save this code in a file with name ranges_with_strings.coffee

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

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c ranges_with_strings.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var my_string, new_string;

  my_string = "Welcome to tutorialspoint";

  new_string = my_string.slice(0, 6);

  console.log(new_string);

}).call(this);

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

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee ranges_with_strings.coffee

在执行时,CoffeeScript 文件会产生以下输出。在这里,你可以观察到结尾值 9 被排除在外。

On executing, the CoffeeScript file produces the following output. In here, you can observe that the end value 9 is excluded.

Welcome to

Comprehensions over Ranges

像对象和数组一样,我们还可以使用解析器迭代一个范围的元素。

As objects and arrays, we can also iterate the elements of a range using comprehensions.

Example

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

Following is an example of using comprehensions over ranges. Here we have created a range and retrieved the elements in it using comprehensions. Save this code in a file with the name 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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c comprehensions_over_ranges.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee comprehensions_over_ranges.coffee

在执行时,CoffeeScript 文件会产生以下输出。在这里,你可以观察到结尾值 9 被排除在外。

On executing, the CoffeeScript file produces the following output. In here, you can observe that the end value 9 is excluded.

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

同样,我们还可以使用解析器的 by 关键字更改这个增量。

In the same way we can also change this increment using the by keyword of comprehensions.

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

CoffeeScript - Splat

在前面的章节中,我们已经看到了如何定义一个函数,调用一个函数和向函数传递参数。一般情况下,我们可以向函数传递固定数量的参数。在编程时,我们可能会遇到需要向这些函数传递可变参数的情况。在 JavaScript 中,我们使用对象来接受函数的可变数量的参数。

In the previous chapters, we have seen how to define a function and invoke a function and pass arguments to it. In general, we can pass a fixed number of arguments to a function. While programming, we may face situations where we need to pass variable arguments to these functions. In JavaScript, we use objects to accept variable number of arguments to a function.

CoffeeScript 提供了一个名为 splats 的特性来向函数传递多个参数。我们通过在参数名后放置三个点来在函数中使用星号,表示为 …​

CoffeeScript provides a feature called splats to pass multiple arguments to functions. We use splats in functions by placing three dots after the argument name and, it is denoted by …​

Syntax

下面给出了使用星号在函数中接受多个参数的语法。

Given below is the syntax of accepting multiple arguments within a function using splats.

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

Example

以下是使用 splats 接受函数中的多个参数的示例。这里我们使用了 splats 定义了一个名为 indian_team() 的函数。我们调用此函数三次,并且每次调用时分别传递 4 个玩家、6 个玩家和全部阵容。由于我们在函数定义中使用了 splats,因此每次调用它时它都会接受可变数量的参数。将此代码保存为一个名为 splats_definition.coffee 的文件。

Following is an example of accepting multiple arguments within a function, using splats. Here we have defined a function named indian_team() using splats. We are calling this function thrice and we are passing 4 players, 6 players, and full squad simultaneously, each time we call it. Since we have used splats in the function definition, it accepts variable number of arguments each time we call it. Save this code in a file with name 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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c splats_definition.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee splats_definition.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

############## 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

Calling Functions using Splats

我们还可以使用 splats 调用函数。为此,我们必须创建一个包含要传递给函数的元素的数组,并且我们必须调用函数,方法是传递点缀有三个点的数组,如下所示。

We can also call a function using splats. For that, we have to create an array holding the elements we need to pass to the function, and we have to call the function by passing the array suffixed by three dots as shown below.

my_function values...

Example

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

Following is an example of calling a function using splats. Save this code in a file with name 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"
 ]

indian_team squad...

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c splats_call.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee splats_call.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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 的文件。

We can also pass tailing arguments to splats. In the example given below, we have passed a tailing argument named last after the splat. Save this example in a file with the name tailing_arguments.coffee

indian_team = (first, second, others..., last) ->
  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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c tailing_arguments.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee tailing_arguments.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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

Comprehensions with Splats

在函数内,我们还可以使用解析在 splat 的元素,如下面的示例所示。将此代码保存为一个名为 splats_comprehensions.coffee 的文件。

Within the function, we can also iterate the elements of a splat using comprehensions as shown in the following example. Save this code in a file with the name 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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c splats_comprehensions.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee splats_comprehensions.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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 语言中内置的一个数据类型。Date 对象作为 new Date( ) 创建。

The Date object is a data-type built into the JavaScript language. Date objects are created as new Date( ).

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

Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.

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

The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755.

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

Similar to other JavaScript objects we can also use the date object in our CoffeeScript code.

Date Methods

以下是 JavaScript 的 Date 对象的各个方法的列表。点击这些方法的名称以获取在 CoffeeScript 中演示其用法的示例。

Following is the list of methods of the Date object of JavaScript. Click on the name of these methods to get an example demonstrating their usage in CoffeeScript.

S.No.

Method & Description

1

getDate()Returns the day of the month for the specified date according to local time.

2

getDay()Returns the day of the week for the specified date according to local time.

3

getFullYear()Returns the year of the specified date according to local time.

4

getHours()Returns the hour in the specified date according to local time.

5

getMilliseconds()Returns the milliseconds in the specified date according to local time.

6

getMinutes()Returns the minutes in the specified date according to local time.

7

getMonth()Returns the month in the specified date according to local time.

8

getSeconds()Returns the seconds in the specified date according to local time.

9

getTime()Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.

10

getTimezoneOffset()Returns the time-zone offset in minutes for the current locale.

11

getUTCDate()Returns the day (date) of the month in the specified date according to universal time.

12

getUTCDay()Returns the day of the week in the specified date according to universal time.

13

getUTCFullYear()Returns the year in the specified date according to universal time.

14

getUTCHours()Returns the hours in the specified date according to universal time.

15

getUTCMinutes()Returns the milliseconds in the specified date according to universal time.

16

getUTCMilliseconds()Returns the minutes in the specified date according to universal time.

17

getUTCMonth()Returns the month in the specified date according to universal time.

18

getUTCSeconds()Returns the seconds in the specified date according to universal time.

19

getYear()Deprecated - Returns the year in the specified date according to local time. Use getFullYear instead.

20

setDate()Sets the day of the month for a specified date according to local time.

21

setFullYear()Sets the full year for a specified date according to local time.

22

setHours()Sets the hours for a specified date according to local time.

23

setMilliseconds()Sets the milliseconds for a specified date according to local time.

24

setMinutes()Sets the minutes for a specified date according to local time.

25

setMonth()Sets the month for a specified date according to local time.

26

setSeconds()Sets the seconds for a specified date according to local time.

27

setTime()Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.

28

setUTCDate()Sets the day of the month for a specified date according to universal time.

29

setUTCFullYear()Sets the full year for a specified date according to universal time.

30

setUTCHours()Sets the hour for a specified date according to universal time.

31

setUTCMilliseconds()Sets the milliseconds for a specified date according to universal time.

32

setUTCMinutes()Sets the minutes for a specified date according to universal time.

33

setUTCMonth()Sets the month for a specified date according to universal time.

34

setUTCSeconds()Sets the seconds for a specified date according to universal time.

35

setYear()Deprecated - Sets the year for a specified date according to local time. Use setFullYear instead.

36

toDateString()Returns the "date" portion of the Date as a human-readable string.

37

toLocaleDateString()Returns the "date" portion of the Date as a string, using the current locale’s conventions.

38

toLocaleString()Converts a date to a string, using the current locale’s conventions.

39

toLocaleTimeString()Returns the "time" portion of the Date as a string, using the current locale’s conventions.

40

toTimeString()Returns the "time" portion of the Date as a human-readable string.

41

toUTCString()Converts a date to a string, using the universal time convention.

CoffeeScript - Math

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

The Math object of JavaScript provides you properties and methods for mathematical constants and functions. Unlike other global objects, Math is not a constructor. All the properties and methods of Math are static and can be called by using Math as an object without creating it.

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

Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method’s argument. We can use the JavaScript’s Math object in our CoffeeScript code to perform math operations.

Mathematical constants

如果我们希望使用任何常用的数学常量,例如 pi 或 e,我们可以通过使用 JavaScript 的 Math 对象来使用它们。

If we want to use any common mathematical constants like pi or e we can use them using the JavaScript’s Math object.

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

Following is the list of the Math constants provided by the Math object of JavaScript

S.No.

Property & Description

1

E Euler’s constant and the base of natural logarithms, approximately 2.718.

2

LN2 Natural logarithm of 2, approximately 0.693.

3

LN10 Natural logarithm of 10, approximately 2.302.

4

LOG2E Base 2 logarithm of E, approximately 1.442.

5

LOG10E Base 10 logarithm of E, approximately 0.434.

6

PI Ratio of the circumference of a circle to its diameter, approximately 3.14159.

7

SQRT1_2 Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.

8

SQRT2Square root of 2, approximately 1.414.

Example

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

The following example demonstrates the usage of the mathematical constants provided by JavaScript in CoffeeScript. Save this code in a file with name 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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c math_example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee math_example.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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 Methods

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

In addition to properties, the Math object also provides methods. Following is the list of methods of the Math object of JavaScript. Click on the name of these methods to get an example demonstrating their usage in CoffeeScript.

S.No.

Method & Description

1

abs()Returns the absolute value of a number.

2

acos()Returns the arccosine (in radians) of a number.

3

asin()Returns the arcsine (in radians) of a number.

4

atan()Returns the arctangent (in radians) of a number.

5

atan2()Returns the arctangent of the quotient of its arguments.

6

ceil()Returns the smallest integer greater than or equal to a number.

7

cos()Returns the cosine of a number.

8

exp()Returns EN, where N is the argument, and E is Euler’s constant, the base of the natural logarithm.

9

floor()Returns the largest integer less than or equal to a number.

10

log()Returns the natural logarithm (base E) of a number.

11

max()Returns the largest of zero or more numbers.

12

min()Returns the smallest of zero or more numbers.

13

pow()Returns base to the exponent power, that is, base exponent.

14

random()Returns a pseudo-random number between 0 and 1.

15

round()Returns the value of a number rounded to the nearest integer.

16

sin()Returns the sine of a number.

17

sqrt()Returns the square root of a number.

18

tan()Returns the tangent of a number.

CoffeeScript - Exception Handling

当一个程序正在运行时,一个异常(或异常事件)是一个突发问题。当一个异常发生时,程序的正常流程被打断,并且程序/应用程序异常终止,这是不推荐的,因此这些异常应被处理。

An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs, the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be handled.

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

An exception can occur for many different reasons. Here are some scenarios where an exception occurs.

  1. A user has entered invalid data.

  2. A file that needs to be opened cannot be found.

Exceptions in CoffeeScript

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

CoffeeScripts supports exception/error handling using the try catch and finally blocks. The functionalities of these blocks are same as in JavaScript, the try block holds the exceptional statements, the catch block has the action to be performed when an exception occurs, and the finally block is used to execute the statements unconditionally.

以下是CoffeeScript中 try catchfinally 块的语法。

Following are the syntaxes of try catch and finally blocks in 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 块被执行。可选的 finally 块会在 try/catch 之后无条件执行。

The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch.

Example

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

The following example demonstrates the Exception handling using try and catch blocks in CoffeeScript. In here, we are trying to use an undefined symbol in CoffeeScript operation and we handled the error occurred using the try and catch blocks. Save this code in a file with the name 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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c Exception_handling.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee Exception_handling.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

exception/error occurred
The STACKTRACE for the exception/error occurred is ::
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\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\coffee-script.js:134:23)
  at compileScript (C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\command.js:224:29)
  at compilePath (C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\command.js:174:14)
  at Object.exports.run (C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\command.js:98:20)
  at Object.<anonymous> (C:\Users\Tutorialspoint\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

The finally block

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

We can also rewrite the above example using finally block. If we do so, the contents of this block are executed unconditionally after try and catch. Save this code in a file with the name 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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c Exception_handling_finally.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee Exception_handling_finally.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

exception/error occurred
The STACKTRACE for the exception/error occurred is ::
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\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\coffee-script.js:134:23)
  at compileScript (C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\command.js:224:29)
  at compilePath (C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\command.js:174:14)
  at Object.exports.run (C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-script\command.js:98:20)
  at Object.<anonymous> (C:\Users\Tutorialspoint\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

The throw Statement

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

CoffeeScript also supports the throw statement. You can use throw statement to raise your builtin exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action.

Example

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

The following example demonstrates the usage of the throw statement in CoffeeScript. Save this code in a file with name 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 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c throw_example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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 文件。

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee throw_example.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

Divided by zero error.

CoffeeScript - Regular Expressions

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

A regular expression is an object that describes a pattern of characters JavaScript supports. In JavaScript, RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text.

Regular Expressions in CoffeeScript

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

The regular expressions in CoffeeScript are same as JavaScript. Visit the following link to see the regular expressions in JavaScript − javascript_regular_expressions

Syntax

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

A regular expression in CoffeeScript is defined by placing the RegExp pattern between the forward slashes as shown below.

pattern =/pattern/

Example

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

Following is an example of regular expressions in CoffeeScript. In here, we have created an expression that finds out the data that is in bold (data between <b> and </b> tags). Save this code in a file with name regex_example.coffee

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

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c regex_example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var input_data, regex, result;

  input_data = "hello how are you welcome to <b>Tutorials Point.</b>";

  regex = /<b>(.*)<\/b>/;

  result = regex.exec(input_data);

  console.log(result);

}).call(this);

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

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee regex_example.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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

heregex

我们使用 JavaScript 提供的语法编写的复杂正则表达式不可读,因此,为了使正则表达式更具可读性,CoffeeScript 为正则表达式提供了一个扩展语法,称为 heregex 。使用此语法,我们可以使用空格打断常规的正则表达式,并且我们还可以在这些扩展的正则表达式中使用注释,从而使它们更加用户友好。

The complex regular expressions we write using the syntax provided by JavaScript are unreadable, therefore to make Regular expressions more readable, CoffeeScript provides an extended syntax for regular expressions known as heregex. Using this syntax, we can break the normal regular expressions using whitespaces and we can also use comments in these extended regular expressions, thus making them more user friendly.

Example

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

The following example demonstrates the usage of the advanced regular expressions in CoffeeScript heregex. In here, we are rewriting the above example using the advanced regular expressions. Save this code in a file with name heregex_example.coffee

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

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c heregex_example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var heregex, input_data, result;

  input_data = "hello how are you welcome to <b> Tutorials Point.</b>";

  heregex = /<b>(.*) <\/b>/;

  result = heregex.exec(input_data);

  console.log(result);

}).call(this);

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

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee heregex_example.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

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

CoffeeScript - Classes and Inheritance

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

JavaScript does not provide the class keyword. We can achieve inheritance in JavaScript using objects and their prototypes. Every object have their own prototype and they inherit functions and properties from their prototypes. Since the prototype is also an object, it also has its own prototype.

尽管原型继承比经典继承强大得多,但对于新手用户来说,它却很困难且容易混淆。

Though the prototypal inheritance is far more powerful than classic inheritance, it is difficult and confusing for novice users.

Classes in CoffeeScript

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

Addressing to this problem, CoffeeScript provides a basic structure known as class which is built using the JavaScript’s prototypes. You can define a class in CoffeeScript using the class keyword as shown below.

class Class_Name

Example

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

Consider the following example, here we have created a class named Student using the keyword class.

class Student

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

If you compile the above code, it will generate the following JavaScript.

var Student;

Student = (function() {
  function Student() {}

  return Student;

})();

Instantiating a class

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

We can instantiate a class using the new operator just like other object oriented programming languages as shown below.

new Class_Name

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

You can instantiate the above created (Student) class using the new operator as shown below.

class Student
new  Student

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

If you compile the above code, it will generate the following JavaScript.

var Student;

Student = (function() {
  function Student() {}

  return Student;

})();

new Student;

Defining a Constructor

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

A constructor is a function that is invoked when we instantiate a class, its main purpose is to initialize the instance variables. In CoffeeScript, you can define a constructor just by creating a function with name constructor as shown below.

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

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

In here, we have defined a constructor and assigned the local variable name to the instance variable.

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

The @ operator is an alias to the this keyword, it is used to point the instance variables of a class.

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

If we place @ before an argument of the constructor, then it will be set as an instance variable automatically. Therefore, the above code can be written simply as shown below −

class Student
  constructor: (@name)->

Example

这是一个CoffeeScript中的构造函数示例。将其另存为名为 constructor_example.coffee 的文件中

Here is an example of a constructor in CoffeeScript. Save it in a file with the name 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

Compiling the code

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

Open command prompt and compile the above example as shown below.

c:\>coffee -c constructor_example.coffee

执行上述命令将生成以下JavaScript。

On executing the above command it will produce the following 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

Executing the Code

在命令提示符上执行以下命令,以运行上述示例。

Run the above example by executing the following command on the command prompt.

coffee constructor_example.coffee

运行后,上述示例将给出以下输出。

On running, the above example gives you the following output.

The name of the student is :Mohammed

Instance Properties

与对象中一样,我们还可以在类中使用属性。这些称作 instance properties

Same as in objects, we can also have properties within a class. And these are known as instance properties.

Example

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

Consider the following example. In here, we have created variables (name, age) and a function (message()) within the class and accessed them using its object. Save this example in a file named 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()

在编译后,上述代码将生成以下输出。

On compiling, the above code generates the following output.

// 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);

Static Properties

我们可以在类中定义静态属性。静态属性的范围局限在类中,我们使用 this keyword 或其别名 @ 符号创建静态函数,并且我们必须通过类名称 Class_Name.property 访问这些属性。

We can define static properties in the class. The scope of the static properties is restricted within the class and we create static functions using the this keyword or its alias @ symbol and we have to access these properties using the class name as Class_Name.property.

Example

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

In the following example, we have created a static function named message. and accessed it. Save it in a file with the name static_properties_example.coffee.

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

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

Open the command prompt and compile the above CoffeeScript file using the following command.

c:\>coffee -c  static_properties_example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following 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,如下所示。

Execute the above coffeeScript in command prompt as shown below.

c:\>coffee static_properties_example.coffee

执行时,上面的示例将输出以下内容。

On executing, the above example gives you the following output.

Hello Raju how are you

Inheritance

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

In CoffeeScript, we can inherit the properties of one class in another class using extends keyword.

Example

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

Following is an Example of inheritance in CoffeeScript. In here, we have two classes namely Add and My_class. We inherited the properties of class named Add in the class My_class, and accessed them using the extends keyword.

#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 中,每当我们创建实例时,都会调用父类的构造函数,直到我们重写它。

CoffeeScript uses prototypal inheritance behind the scenes. In CoffeeScript, whenever we create instances, the parent class’s constructor is invoked until we override it.

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

We can invoke the constructor of the parent class from the subclass, using the super() keyword as shown in the example given below.

#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()

Dynamic Classes

CoffeeScript 使用原型继承自动继承类的所有实例属性。这确保了类的动态性;即使在创建子类之后向父类添加属性,该属性仍会传播到所有继承的子类。

CoffeeScript uses prototypal inheritance to automatically inherit all the instance properties of a class. This ensures that classes are dynamic; even if you add properties to a parent class after a child has been created, the property will still be propagated to all of its inherited children.

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 代码。

On executing, the above CoffeeScript generates the following JavaScript code.

// 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 is a web development technique for creating interactive web applications.

  1. AJAX stands for *A*synchronous *Ja*vaScript and *X*ML. It is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script.

  2. Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display.

  3. Conventional web applications transmit information to and from the server using synchronous requests. It means you fill out a form, hit submit, and get directed to a new page with new information from the server.

  4. With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.

  5. XML is commonly used as the format for receiving server data, although any format, including plain text, can be used.

  6. AJAX is a web browser technology independent of web server software.

  7. A user can continue to use the application while the client program requests information from the server in the background.

  • * *一般来说,我们使用jQuery来使用Ajax。以下是Ajax和jQuery的一个例子

In general, we use jQuery to work with Ajax. Following is an example of Ajax and 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() 初始化了一个Ajax请求到指定的URL /coffeescript/result.html 文件。加载此文件后,所有内容将被填充到带ID舞台的<div>标记中。假设我们的/jquery/result.html文件只有一行HTML −

Here load() initiates an Ajax request to the specified URL /coffeescript/result.html file. After loading this file, all the content would be populated inside <div> tagged with ID stage. Assuming that our /jquery/result.html file has just one HTML line −

<h1>THIS IS RESULT...</h1>
  • * *当你点击给定的按钮,result.html文件就会被加载。

When you click the given button, then result.html file gets loaded.

CoffeeScript with Ajax

  • * *我们可以使用CoffeeScript重新编写上面的示例,如下所示。

We can rewrite the above example using CoffeeScript as shown below.

<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 is a fast and concise library/framework built using JavaScript created by John Resig in 2006 with a nice motto − Write less, do more.

jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. Visit our jQuery tutorial to know about jQuery.

We can also use CoffeeScript to work with jQuery. This chapter teaches you how to use CoffeeScript to work with jQuery.

Using CoffeeScript with jQuery

Though jQuery solves the browser issues, using it with JavaScript which have some bad parts is a bit problematic. Using CoffeeScript instead of JavaScript is a better idea.

使用 CoffeeScript 使用 jQuery 时请牢记以下要点。

Keep the following points in mind while converting the to be while using jQuery with CoffeeScript.

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

The $ symbol indicates the jQuery code in our application. Use this to separate the jQuery code from the scripting language as shown below.

$(document).ready

在 CoffeeScript 中,除了在使用带有参数调用的函数和处理模棱两可代码时,不需要使用括号,且我们必须使用一个箭头标记(如降所示)替代函数定义 function()

There is no need of using braces in in CoffeeScript except while calling the functions with parameters and dealing with the ambiguous code and we have to replace the function definition function() with an arrow mark as shown below.

$(document).ready ->

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

Remove the unnecessary return statements, since CoffeeScript implicitly returns the tailing statements of a function.

Example

下面是一个 JavaScript 代码,其中 <div> 元素被插入到所点击元素之前 −

Following is an JavaScript code where <div> elements are being inserted just before the clicked element −

<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 代码,如下所示

Now, we can convert the above code into CoffeeScript code as shown below

 <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>

执行此代码会给你以下输出。

On executing, this gives you the following output.

What is Callback?

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

Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is such a way that they supports callbacks.

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

For example, a function to read a file may start reading file and return the control to execution environment immidiately so that next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result.

Blocking Code Example

创建一个名为 input.txt 的文本文件,内容如下

Create a text file named input.txt having following content

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

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

Create a js file named main.js which has the following code −

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

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

Now run the main.js to see the result −

$ node main.js

验证输出。

Verify the Output.

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

Non-Blocking Code Example

创建一个名为 input.txt 的文本文件,内容如下

Create a text file named input.txt having following content

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

将main.js文件更新为以下代码:

Update main.js file to have following code −

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 来查看结果 −

Now run the main.js to see the result −

$ node main.js

验证输出。

Verify the Output.

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

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

These two examples explain the concept of blocking and non-blocking calls. The first example shows that the program blocks until it reads the file and then only, it proceeds to end the program, whereas in the second example, the program does not wait for file reading but it just proceeded to print "Program Ended".

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

Thus, a blocking program executes very much in sequence. From programming point of view, its easier to implement the logic but non-blocking programs do not execute in sequence. In case a program needs to use any data to be processed, it should be kept within the same block to make it sequential execution.

CoffeeScript - MongoDB

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

MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document. For more information read our MongoDB Tutorial.

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

In this chapter you will learn how to communicate with MongoDB database using CoffeeScript.

Installation

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

The MongoDB database can be integrated with CoffeeScript using Node.js 2.0 driver of MongoDB. First of all you need to install MongoDB in your system, by referring the environment chapter of our MongoDB tutorial.

在成功安装MongoDB后,浏览其 bin 文件夹(如果您没有设置路径),并按照如下所示启动MongoDB服务。

After installing MongoDB successfully browse through its bin folder (if you haven’t set the path) and start the MongoDB service as shown below.

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

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

Finally install MongoDB driver and it’s dependencies by executing the following NPM command in the command prompt.

npm install mongodb --save

Connecting to MongoDB

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

In order to connect to MongoDB, first of all create MongoClient using this, invoke the connect() function. This function accepts url, and a callback function as parameters.

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

Following CoffeeScript code shows how to connect to MongoDB server. If the MongoDB server is running in your system this program establishes a connection to the server.

#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 的文件中,然后按以下所示执行。如果数据库创建成功,将会显示以下消息

Save the above code in a file with name connect_db.coffee and execute it as shown below. If database is successfully created then it will give following message

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

Creating a Collection

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

A collection in MongoDB holds the documents we store in it. You can create a collection by using the collection() function. This function accepts a string argument that represents the name of the collection we want to create.

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

Following CoffeeScript code shows how to create a collection in MongoDB. In case of any errors, they will be displayed on the console.

#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 的文件中,然后按以下所示执行。如果集合创建成功,将会显示以下消息

Save the above code in a file with name create_collection.coffee and execute it as shown below. If the collection is created successfully then it will give following message

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

Inserting Documents

可以在 MongoDB 中向集合中插入文档,你需要调用名为 insert() 的函数,并按需传入要插入的文档列表,作为参数。

You can inset documents in to a collection in MongoDB you need to invoke a function named insert() by passing the list of documents that are needed to be inserted, as parameters.

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

Following CoffeeScript code shows how to insert documents in to a collection named My_collection. In case of any errors, they will be displayed on the console.

#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 的文件中,并按照以下方式执行它。如果文档插入成功,则会显示以下消息

Save the above code in a file with name insert_documents.coffee and execute it as shown below. If the documents are inserted successfully then it gives following message

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

Reading Documents

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

You can retrieve the documents that are stored in MongoDB using a function named find(). The following CoffeeScript code shows how to retrieve the records that are stored in 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 的文件中,并按照以下方式执行它。此程序按指定集合检索所需的文档并按照以下方式显示它。

Save the above code in a file with name read_documents.coffee and execute it as shown below. This programs retrieves the required document in the specified collection and displays it as shown below.

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

你还可以通过按照以下方式执行 find() 函数来读取特定集合中存在的文档,而不向它传递任何参数。

You can also read all the documents existing in a particular collection by executing the find() function with out passing any arguments to it as shown below.

#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 的文件中,并按照以下方式执行它。此程序按指定集合检索所有文档并按照以下方式显示它。

Save the above code in a file with name read_all_documents.coffee and execute it as shown below. this programs retrieves all the documents in the specified collection and displays it as shown below.

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' } ]

Updating Documents

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

You can update the documents that are stored in MongoDB using a function named update(). Following CoffeeScript code shows how to update the records that are stored in 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 名为员工的城市从 Hyderabad 更新为 Delhi。

This program updates the city of the employee named Ram from Hyderabad to Delhi.

将上面的代码保存在名为 update_documents.coffee 的文件中,并按照以下方式执行它。此程序按指定集合检索文档并按照以下方式显示它。

Save the above code in a file with name update_documents.coffee and execute it as shown below. this programs retrieves the documents in the specified collection and displays it as shown below.

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

更新后,如果你执行 read_documents.coffee 程序,则你会观察到名为 Ram 的人的城市名从 Hyderabad 更新为 Delhi

After updating, if you execute the read_documents.coffee program, then you will observe that the city name of the person named Ram is updated from Hyderabad to 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' } ]

Deleting Documents

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

You can delete all the documents from the collection using the remove() function. Following CoffeeScript code shows how to delete all the records that are stored in 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 的文件中,并按照以下方式执行它。此程序删除指定集合中的所有文档,显示以下消息。

Save the above code in a file with name delete_documents.coffee and execute it as shown below. this programs removes all the documents in the specified collection displaying the following messages.

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

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

After deleting, if you execute the read_documents.coffee program, then you will get an empty collection as shown below.

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

CoffeeScript - SQLite

SQLite 是一个轻量级的、基于架构的关系数据库引擎。作为网络浏览器中本地存储的嵌入式数据库软件,它是一个热门选择。

SQLite is a lightweight, schema-based relational database engine. It is a popular choice as embedded database software for local storage in web browsers.

与许多其他数据库管理系统不同,SQLite 不是一个客户端-服务器数据库引擎。有关详细信息,请阅读我们的链接:../sqlite/sqlite_overview.htm [SQLite 教程]

Unlike many other database management systems, SQLite is not a client–server database engine. For more information read our link:../sqlite/sqlite_overview.htm [SQLite Tutorial]

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

In this chapter you will learn how to communicate with SQLite database using CoffeeScript.

Installation

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

The SQLite3 database can be integrated with CoffeeScript using node-sqlite3 module. This module works with Node.js v0.10.x, v0.12.x, v4.x, and v5.x. This module caters various functions to communicate with SQLite3 using CoffeeScript, in addition to this it also provides an Straightforward query and parameter binding interface, and an Query serialization API.

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

You can install the node-sqlite3 module using npm as shown below.

npm install sqlite3

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

To use sqlite3 module, you must first create a connection object that represents the database and this object will help you in executing all the SQL statements.

Connecting to Database

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

In order to connect to SQLite database first of all create its package by invoking the require() function of the node-sqlite3 module and pass the string sqlite3 as a parameter to it. Then connect to a database by passing the name of the database to sqlite3.Database() construct.

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

Following CoffeeScript code shows how to connect to an existing database. If database does not exist, then it will be created with the given name test.db, opened and finally the database object will be returned.

#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 的文件,并按如下所示执行该代码。如果数据库成功创建,那么它将产生以下消息:

We can also supply :memory: to create an anonymous in-memory database and, an empty string to create anonymous disk-based database, instead of test.db. Save the above code in a file with name create_db.coffee and execute it as shown below. If the database is successfully created, then it will produce the following message −

c:\> coffee create_db.coffee
Successfully connected

Creating a Table

你可以通过 CoffeeScript 中的 run() 函数创建 SQLite 数据库中的表。以字符串格式将创建表的查询传递给该函数。

You can create a table in SQLite database through CoffeeScript using the run() function. Pass the query to create a table to this function in String format.

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

The following CoffeeScript program will be used to create a table in previously test.db database −

#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() 函数关闭连接。

The serialize() function sets the database in serialized mode. In this mode when ever a callback encounters, it will be called immediately. The queries in that callback are executes serially. Soon the function returns The database will be set to normal mode again. After completing the transaction we need to close the connection using close() function.

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

Save the above code in a file with name create_table.coffee and execute it as shown below. This will create a table named STUDENT in the database test.db displaying the following messages.

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

Inserting / Creating Data

可以通过执行插入语句将数据插入 SQLite 数据库中,方法是使用 CoffeeScript 代码。为此,可以使用准备 SQL 语句的 prepare() 函数。

You can insert data into SQLite database through CoffeeScript code by executing the insert statement. To do so we can use the prepare() function which prepares SQL statements.

它还接受具有绑定变量 ( ? ) 的查询,可以使用 run() 函数附加值到这些变量。可以使用预处理语句插入多条记录,插入所有记录后,需要使用 finalize() 函数最终确定预处理语句。

It also accepts query with bind variables (?), values to these variables can be attached using run() function. You can insert multiple records using prepared statement, and after inserting all the records, you need to finalize the prepared statement using finalize() function.

以下 CoffeeScript 程序展示了如何插入到上一个示例中创建的 STUDENT 表中记录。

The following CoffeeScript program shows how to insert records in the table named STUDENT created in previous example.

#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 的表格,显示以下消息。

Save the above code in a file with name insert_data.coffee and execute it as shown below. This will populate the table named STUDENT displaying the following messages.

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

Reading / Retrieving Data

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

You can get the data from an SQLite table using the each() function. This function accepts an optional callback function which will be called on each row.

以下 CoffeeScript 程序展示了如何从上一个示例中创建的 STUDENT 表中提取和显示记录

The following CoffeeScript program shows how we can fetch and display records from the table named STUDENT created in the previous example

#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 的表中的所有记录,并在控制台按如下方式显示。

Save the above code in a file with name retrive_data.coffee and execute it as shown below. This retrieves all the records in the table named STUDENT and displays on the console as follows.

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

Updating Data

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

The following CoffeeScript code shows how we can use UPDATE statement to update any record and then fetch and display updated records in the table named 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 的学生的城市,并在更新操作后按如下所示在表中显示所有记录。

Save the above code in a file with name update_data.coffee and execute it as shown below. This updates the city of the student named Ram and displays all the records in the table after update operation as follows.

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

Deleting Data

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

The following CoffeeScript code shows how we can use DELETE statement to delete any record and then fetch and display remaining records from the table named 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 的学生的记录,并在删除操作后按如下所示显示表中所有余下的记录。

Save the above code in a file with name delete_data.coffee and execute it as shown below. It deletes the record of the student named Ram and displays all the remaining in the table after delete operation as follows.

Successfully connected
Record deleted
The contents of the table STUDENT after delete operation are ::
2: Robert, Mumbai
3: Rahim, Bangalore