2013-04-22 43 views
1

这可能是一个非常简单的答案的问题,但我只是无法理解为什么这不工作;简单循环咖啡脚本不工作

sort = (arr) -> 
    word for word in arr 
     if word is 'some word' 
       console.log 'word present' 

所有我想要做的是CONSOLE.LOG是一个词存在数组中,但我刚开始

Parse error on line 4: Unexpected 'INDENT' 

可能有人请解释一下,或给我一个提示,这是为什么不工作。 谢谢:)

+0

我想肯定有空白问题 – 2013-04-22 12:10:33

+0

@ The-Val不,它不是问题是与循环 – TheHippo 2013-04-22 12:12:16

回答

4

你的代码应该看起来像这样。 (仔细观察的循环):

sort = (arr) -> 
    for word in arr 
     if word is 'some word' 
      console.log 'word present' 

或简写:

sort = (arr) -> 
    for word in arr when word is 'some word' 
     console.log 'word present' 

你试图使用的语法是理解。

下面的例子在那里你可以保存数组的每个元素相匹配的第一个字母:

sort = (arr) -> 
    firstLetter = (word[0] for word in arr when word is 'some word') 

编辑:
从上面合并的例子:

sort = (arr) -> 
    console.log word for word in arr when word is 'some word' 
+0

注意:我总是发现它有用于使用“试用coffeescript”选项在t他coffeescript主页。它让您快速了解实际发生的情况。 – TheHippo 2013-04-22 12:17:19

+0

谢谢!新的咖啡,但你的答案帮助! – miner 2013-04-22 12:26:18

+0

@miner很高兴能帮到你。 CoffeeScript非常棒,但需要一点点才能真正了解它。 – TheHippo 2013-04-22 12:28:37