2012-01-17 31 views
0

我在Rails应用程序中使用CoffeeScript。如何JavaScript的转换为CoffeeScript的两种情况:如何将JavaScript转换为CoffeeScript两种情况

var colIndex = 0, 
    colRight = 0, 
    cols = this.grid.columnX, 
    len = cols.length, 
    cmatch = false; 

for (len; colIndex < len; colIndex++) { 
    colRight = cols[colIndex].x + cols[colIndex].w; 
    if (xy[0] < colRight) { 
     cmatch = true; 
    break; 
    } 
} 

setTimeout(function() { 
    d.scrollTop = st; 
}, 10); 

预先感谢您的帮助!

+0

可能重复[?是否有转换JavaScript来的CoffeeScript工具(http://stackoverflow.com/questions/3510906/is-there-a-tool -for-conversion-javascript-to-coffeescript) – 2012-01-17 10:46:26

回答

1

1.CoffeeScript支持for in迭代在一个数组上,所以你根本不需要colIndexlen

colRight = 0 
cols = @grid.columnX 
cmatch = false 

for col in cols 
    colRight = col.x + col.w 
    if xy[0] < colRight 
    cmatch = true 
    break 

2.

setTimeout (-> d.scrollTop = st), 10 
+0

setTimeout看起来不错,但你会忽略OP可能实际上想要匹配项目的索引。看到我的答案,提供了一个解决方案。 – 2012-01-18 22:03:00

0

有一个网站做这项工作js2coffee

的答案是:

colIndex = 0 
colRight = 0 
cols = @grid.columnX 
len = cols.length 
cmatch = false 
len 
while colIndex < len 
    colRight = cols[colIndex].x + cols[colIndex].w 
    if xy[0] < colRight 
    cmatch = true 
    break 
    colIndex++ 
setTimeout (-> 
    d.scrollTop = st 
), 10 
0

这里是我的刺吧:

for col, idx in @grid.columnX when xy[0] < colRight = (col.x + col.w) 
    cmatch = idx 
    break 

循环后因此,C匹配要么是未定义或比赛的指数,而colRight将匹配山坳的右侧,或者最后一个山坳的右侧如果找不到匹配项。

这里有一个小提琴在玩:http://jsfiddle.net/fNSXE/1/

相关问题