Nathan Campos
Nathan Campos

Reputation: 29497

For Loops Using Javascript

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?

Upvotes: 2

Views: 191

Answers (3)

Trevor Burnham
Trevor Burnham

Reputation: 77416

Š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]

Upvotes: 1

Acorn
Acorn

Reputation: 50497

I would do it like this:

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

Upvotes: 3

Šime Vidas
Šime Vidas

Reputation: 185893

Try this:

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

Upvotes: 2

Related Questions