In Javascript, the "for (attr in this)" is often dangerous to use... I agree. That's one reason I like Coffeescript. However, I'm programming in Coffeescript and have a case where I need Javascript's "for (attr in this)". Is there a good way to do this in Coffeescript?
What I am doing now is writing a bunch of logic in embedded raw Javascript, such as:
...coffeescript here...
for (attr in this) {
if (stuff here) {
etc
}
}
It'd be nice to use as little Javascript as possible... any suggestions for how I can achieve this and maximize my use of Coffeescript?
You can use
for x in y
orfor x of y
depending on how you want to interpret a list of elements. The newest version of CoffeeScript aims to solve this problem, and you can read about its new use with an issue (that has since been implemented and closed) here on GitHubInstead of
for item in items
which iterates through arrays, you can usefor attr, value of object
, which works more likefor in
from JS.Compiled: https://gist.github.com/62860f0c07d60320151c
It accepts both the key and the value in the loop, which is very handy. And you can insert the
own
keyword right after thefor
in order to enforce anif object.hasOwnProperty(attr)
check which should filter out anything from the prototype that you don't want in there.Squeegy's answer is correct. Let me just amend it by adding that the usual solution to JavaScript's
for...in
being "dangerous" (by including prototype properties) is to add ahasOwnProperty
check. CoffeeScript can do this automatically using the specialown
keyword:is equivalent to the JavaScript
When in doubt about whether you should use
for...of
orfor own...of
, it's generally safer to useown
.