2

I'm trying to convert this code from Javascript to CoffeeScript:

for (var i = 0; i < names.length; i++) {
    str += "Hello" + names[i] + "!<br />";
}

But at the CoffeeScript project home page there is only a simple example of how to do for loops and I can't understand it quite well too, so how can I make convert that to CoffeeScript?

3 Answers 3

3

I would do it like this:

msg = ("Hello #{name}!" for name in names).join '\n'

Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

str += 'Hello' + name + '!<br />' for name in names

6 Comments

I think CoffeeScript has built in string interpolation, so you should also be able to do str += "Hello ${name}!<br />" ...
@CD That's a neat feature :) @Nathan Does this string interpolation thing work for you? If yes, I'll put it in my answer....
Nope, the result was Hello ${name}!<br />Hello ${name}!<br />Hello ${name}!<br />
@Nathan Try this: str += "Hello #{name}!<br />". This article suggests that the # sign is used for string interpolation, not the $ sign...
Using # I got this: Hello Nathan,John,Michel!<br />
|
1

Šime and Acorn beat me to the best answers, but it's worth adding that the literal translation of your code would be

for i in [0...names.length]
  str += "Hello #{names[i]}!<br />"

or using postfix rather than indentation,

str += "Hello #{names[i]}!<br />" for i in [0...names.length]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.