【问题标题】:Having trouble amking if statement within loop work in coffeescript在咖啡脚本中循环工作的 if 语句遇到问题
【发布时间】:2016-06-22 21:46:31
【问题描述】:

我使用的是 Rails 4.2.3。我有这个 Javascript

  for (i = 0; i < listItems.length; i++) {
    if (listItems[i] === window.location.pathname)
      return i
  }

我想变成咖啡脚本。所以我尝试了

if window.location.pathname in [listItems[i]] return i for i in [0...listItems.length] 

但在运行此程序时,我收到错误“SyntaxError: [stdin]:77:3: unexpected if”。翻译这个 JS 的正确方法是什么?

【问题讨论】:

标签: loops if-statement coffeescript


【解决方案1】:

首先,要在同一行的 if 语句中使用 return,您应该使用“then”关键字。 其次,您的代码逻辑似乎不正确。你想要的是类似的东西

for i in [0...listItems.length]
   return i if listItems[i] is window.location.pathname

它也比一条复杂的行更容易阅读:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2014-05-27
    • 2012-06-18
    • 1970-01-01
    相关资源
    最近更新 更多