【问题标题】:simple for loop in coffee script not working咖啡脚本中的简单 for 循环不起作用
【发布时间】:2013-04-22 20:22:14
【问题描述】:

这可能是一个答案非常简单的问题,但我无法理解为什么这不起作用;

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

我想要做的就是 console.log 是数组中存在一个单词,但我只是得到 ​​p>

Parse error on line 4: Unexpected 'INDENT'

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

【问题讨论】:

  • 我认为肯定有空白问题
  • @The-Val 不,问题不在于循环

标签: coffeescript


【解决方案1】:

您的代码应如下所示。 (仔细观察循环):

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'

【讨论】:

  • 注意:我总是发现使用咖啡脚本主页上的“试用咖啡脚本”选项很有帮助。它可以让您快速了解实际发生的情况。
  • 谢谢!刚接触咖啡,但您的回答有所帮助!
  • @miner 很高兴我能帮上忙。 CoffeeScript 很棒,但要真正了解它需要一点时间。
猜你喜欢
  • 1970-01-01
  • 2012-06-14
  • 1970-01-01
  • 2012-06-18
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多