20

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.

3
  • Not a coffee-script programmer, but shouldn't it work just as it is? Commented Jun 14, 2012 at 21:57
  • No, coffeescript has other loops that it converts to js loops. usually in a convenient way. Commented Jun 14, 2012 at 21:58
  • 1
    Then +1, I would like to hear the answer as well... :) Commented Jun 14, 2012 at 21:59

2 Answers 2

32
console.log "#{k}=#{v}" for k, v of o
Sign up to request clarification or add additional context in comments.

Comments

28

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

2 Comments

right, and now i even find it in the dense docu, thx a lot, both helpful
That is kind of crazy since js is kind of the opposite. For...in is for objects and For...of is for arrays (iterables)

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.