citykid
citykid

Reputation: 11132

Coffeescript . for/in loop

Anybody knows if it is possible to get a

javascript for/in loop

from coffeescript?

Actually would like to write the js function

function logobject(o) {
   for (p in o)
     console.log(p + "=" + o[p])
}

in coffeescript.

Upvotes: 20

Views: 10136

Answers (2)

Niko
Niko

Reputation: 26730

This might be a bit confusing for CoffeeScript newbies, but the for..in loop is used to iterate over arrays, while the for..of loop is used to iterate over objects.

logobject = (o) ->
  console.log key + "=" + value for key, value of o

Also, to restrict this to own properties of the object (skips inherited properties via hasOwnProperty()), the "own" keyword can be added:

for own key, value of o

Upvotes: 28

Pickels
Pickels

Reputation: 34680

console.log "#{k}=#{v}" for k, v of o

Upvotes: 32

Related Questions