CoffeeScript : unexpected INDENT error

泄露秘密 提交于 2019-12-25 02:21:25

问题


I am trying out CoffeeScript in my Rails 3.1 app. However, I am not able to figure out how to break long lines in CoffeeScript without getting the above error

For example, how/where would you break the following line of code

alert x for x in [1,2,3,4,5]  when x > 2

if you wanted something like

alert x for
  x in [1,2,3,4,5]
  when x > 2

In my vimrc, I have set

 ts=2, sw=2 and I expand tabs. 

And yet, I cannot get something as simple as the line above to work properly.

My Gemfile.lock shows coffee-script-2.2.0 with coffee-script-source 1.1.3


回答1:


If you have a comprehension that is too long you can break it with \ as @brandizzi mentions, but I think you might have better luck just using comprehensions where they make sense and expanding to 'regular' code where they don't:

alert x for x in [1,2,3,4,5]  when x > 2

...can be rewritten as...

for x in [1,2,3,4,5]
  alert x if x > 2

...or even...

for x in [1,2,3,4,5]
  if x > 2
    alert x

In other words, comprehensions are syntactic sugar for short, concise snippets - you don't have to use them for everything.




回答2:


You're trying to spread a comprehension out over multiple lines, which isn't allowed. It either needs to be on one line, or be a proper loop. Your one line version works as expected, so I'll show the loop version:

for x in [1..5] when x > 2
  alert x

You may find it helpful to toss small things like this into the CoffeeScript compiler at http://jashkenas.github.com/coffee-script/ to see if they're compiling to what you'd expect.




回答3:


I do not understand the inner details of CoffeeScript syntax, so I cannot say what is going wrong in detail. The error is a bit clear, however: you cannot put a newline between the for and its iterator variable. Also, you did not get this error yet, but you cannot put a newline between the iterated object and the when clause. However, if you really want to do it, it is easy: put backslashes at the end of the first and second lines.

console.log x for \
    x in [1,2,3,4,5] \
    when x > 2


来源:https://stackoverflow.com/questions/8550738/coffeescript-unexpected-indent-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!