如何使用 JavaScript for (attr in this) 与 Coffeescript
在 Javascript 中,“for (attr in this)”使用起来通常很危险......我同意。这是我喜欢 Coffeescript 的原因之一。然而,我正在使用 Coffeescript 进行编程,并且有一个情况需要 Javascript 的“for (attr in this)”。在 Coffeescript 中有没有好的方法可以做到这一点?
我现在正在做的是在嵌入式原始 Javascript 中编写一堆逻辑,例如:
...coffeescript here...
for (attr in this) {
if (stuff here) {
etc
}
}
最好使用尽可能少的 Javascript...有关如何实现这一目标并最大化使用 Coffeescript 的任何建议吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
for attr, value of object
,而不是迭代数组的for item in items
,它的工作方式更像是 JS 中的for in
。编译后: https://gist.github.com/62860f0c07d60320151c
它在循环中同时接受key和value,这一点很便利。您可以在
for
之后插入own
关键字,以强制执行if object.hasOwnProperty(attr)
检查,该检查应过滤掉任何内容来自您不想要的原型。Instead 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.斯奎吉的回答是正确的。让我修改一下,添加一个
hasOwnProperty
检查来解决 JavaScript 的for...in
的“危险”(通过包含原型属性)的情况。 CoffeeScript 可以使用特殊的own
关键字自动执行此操作:相当于 JavaScript
当您不确定是否应该使用
for...of
还是for own 时。 ..of
,通常使用自己的
更安全。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
.您可以使用
for x in y
或for x of y
,具体取决于您想要如何解释元素列表。最新版本的 CoffeeScript 旨在解决这个问题,您可以通过一个问题了解其新用途(该问题已实现并关闭)GitHub 上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 GitHub