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'

有人可以解释或提示我为什么这不起作用。谢谢 :)

4

1 回答 1

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'
于 2013-04-22T12:16:03.697 回答