目录

show example

就像postfix ifunless ,CoffeeScript提供了Comprehensions的后缀形式,它在编写代码时很方便。 使用这个,我们可以在一行中编写for..in理解,如下所示。

#Postfix for..in comprehension
console.log student for student in ['Ram', 'Mohammed', 'John']
#postfix for..of comprehension
console.log key+"::"+value for key,value of { name: "Mohammed", age: 24, phone: 9848022338}

Postfix for..in理解

下面的示例演示了CoffeeScript提供的for..in理解的postfix形式的用法。 将此代码保存在名为for_in_postfix.coffee的文件中

console.log student for student in ['Ram', 'Mohammed', 'John']

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

c:\> coffee -c for_in_postfix.coffee

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

// Generated by CoffeeScript 1.10.0
(function() {
  var i, len, ref, student;
  ref = ['Ram', 'Mohammed', 'John'];
  for (i = 0, len = ref.length; i < len; i++) {
    student = ref[i];
    console.log(student);
  }
}).call(this);

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

c:\> coffee for_in_postfix.coffee 

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

Ram
Mohammed
John 

Postfix for..of理解

下面的示例演示了CoffeeScript提供的for..of理解的postfix形式的用法。 将此代码保存在名为for_of_postfix.coffee的文件中

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

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

c:\> coffee -c for_of_postfix.coffee

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

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

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

c:\> coffee for_of_postfix.coffee 

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

name::Mohammed
age::24
phone::9848022338
↑回到顶部↑
WIKI教程 @2018