声明和说明 |
for..in comprehensions
for..in 推导式是 CoffeeScript 中推导式的基本形式,使用我们可以迭代列表或数组的元素。
|
for..of comprehensions
就像数组一样,CoffeeScriptScript 提供了一个容器来存储称为对象的键值对。我们可以使用 CoffeeScript 提供的
for..of 推导式迭代对象。
|
列表推导
CoffeeScript 中的
列表推导用于映射数组对象到另一个数组。
|
for student,i in [element1, element2, element3]
for student,i in ['Ram', 'Mohammed', 'John'] console.log "The name of the student with id "+i+" is: "+student
c:\> coffee-c for_in_index.coffee
// 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);
c:\> coffee for_in_index.coffee
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 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}
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()
c:\> coffee-c example.coffee
// 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);
c:\> coffee example.coffee
The contents of the variable names are ::Ram,Mohammed,John The value returned by the function is Ram
array = (num for num in [1..10] by 2)
console.log array
c:\> coffee-c by_keyword_example.coffee
// 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);
c:\> coffee by_keyword_example.coffee
[ 1, 3, 5, 7, 9 ]