如何在coffeescript中使用循环块

时间:2013-06-27 06:39:15

标签: javascript coffeescript underscore.js

我想在coffeescript函数中返回for循环。但是转发器发出错误。

breaker = {}
nativeForEach      = Array.prototype.forEach

_each = (obj, iterator, context) ->
    return if (obj == null)
    if nativeForEach and obj.forEach is nativeForEach
      obj.forEach(iterator, context)
    else if obj.length is +obj.length
      # seems the for loop and return statement is wrong
      for item, i in obj
        if iterator.call(context, item, i, obj) == breaker
          return
    else
      for key of obj
        if _has(obj, key)
          return if iterator.call(context, obj[key], key, obj) is breaker  

但是coffee-script-redux说:

D:\dev\nodejs\node_modules\coffee-script-redux\lib\compiler.js:153
    throw new Error('expr: Cannot use a ' + s.type + ' as a value');
          ^
Error: expr: Cannot use a ReturnStatement as a value
    at expr (D:\dev\nodejs\node_modules\coffee-script-redux\lib\compiler.js:153:11)
    at expr (D:\dev\nodejs\node_modules\coffee-script-redux\lib\compiler.js:123:18)
    at expr (D:\dev\nodejs\node_modules\coffee-script-redux\lib\compiler.js:135:52)
    at makeReturn (D:\dev\nodejs\node_modules\coffee-script-redux\lib\compiler.js:182:35)
    at makeReturn (D:\dev\nodejs\node_modules\coffee-script-redux\lib\compiler.js:161:80)
    at makeReturn (D:\dev\nodejs\node_modules\coffee-script-redux\lib\compiler.js:165:42)
    at makeReturn (D:\dev\nodejs\node_modules\coffee-script-redux\lib\compiler.js:165:96)
    at makeReturn (D:\dev\nodejs\node_modules\coffee-script-redux\lib\compiler.js:163:91)
    at class$.exports.Compiler.expression (D:\dev\nodejs\node_modules\coffee-script-redux\lib\compiler.js:1094:20)
    at class$.<anonymous> (D:\dev\nodejs\node_modules\coffee-script-redux\lib\compiler.js:2325:86)

我以为我知道coffeescript循环语句,但它绝对让我困惑。 请帮帮我!

编辑:实际上,我的代码是undercore.js的_.each方法的重写coffeescript版本。有人可以在coffeescript中重写它吗?

0 个答案:

没有答案