在 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 的任何建议?
最佳答案
而不是 for item in items
遍历数组,您可以使用 for attr, value of object
, 更像 for in
来自 JS。
for own attr, value of this
if attr == 'foo' && value == 'bar'
console.log 'Found a foobar!'
编译:https://gist.github.com/62860f0c07d60320151c
它接受循环中的键和值,这非常方便。您可以插入
own
for
之后的关键字为了执行 if object.hasOwnProperty(attr)
检查哪个应该从原型(prototype)中过滤掉你不想要的任何东西。
关于coffeescript - 如何在 Coffeescript 中使用 Javascript 的 for (attr in this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5752059/