问题你想通过一个 for 循环来迭代数组、对象或范围。解决方案# for(i = 1; i<= 10; i++)x for x in [1..10]# => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]# To count by 2# for(i=1; i<= 10; i=i+2)x for x in [1..10] by 2# => [ 1, 3, 5, 7, 9 ]# Perform a simple operation like squaring each item.x * x for x in [1..10]# = >
问题当你在 CoffeeScript 上创建了一个函数,并希望将它用在有网页浏览器的客户端和有 Node.js 的服务端时。解决方案以下列方法输出函数:# simpleMath.coffee# these methods are privateadd = (a, b) -> a + bsubtract = (a, b) -> a - bsquare = (x) -> x * x# create a namespace to export our public methodsSimpleMath = exports?
for in 语句可以遍历对象中所有的属性。枚举包括函数和原型属性。var fruit = { apple: 2, orange:5, pear:1},sentence = 'I have ',quantity;for (kind in fruit){ quantity = fruit[kind]; sentence += quantity+' '+kind+ (quantity===1?'':'s')+ ', ';} // The following line removes the trailing coma.
There are two ways to create an object in JavaScript:在Javascript中,有两种方法去创建一个 对象 :字面上 var object = {}; // 是的,简单是使用一对大括号!注意: 这是 推荐 的方法面向对象 var object = new Object();注意: 这很像Java
只要特殊条件为真,While循环就一直执行代码块。while(condition){ // 只要条件为真就继续执行}举个例子,以下代码会一直执行,只要变量 i 小于5: var i = 0, x = "";while (i < 5) { x = x + "The number is " + i; i++;}Do/While循环是while循环的变体。这种循环将先检查条件是否为真,再执行代码块。