2013-04-22 41 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