17

在 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 的任何建议?

4

3 回答 3

17

您可以使用代替for item in itemswhich 遍历数组,for attr, value of object它的工作方式更像for inJS。

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)检查,该检查应该从原型中过滤掉您不想要的任何内容。

于 2011-04-22T16:59:14.363 回答
6

Squeegy 的回答是正确的。让我通过添加对 JavaScript for...in“危险”(通过包含原型属性)的通常解决方案来添加一个hasOwnProperty检查来修改它。CoffeeScript 可以使用特殊own关键字自动执行此操作:

for own attr of this
  ...

相当于 JavaScript

for (attr in this) {
  if (!Object.prototype.hasOwnProperty(this, attr)) continue;
  ...
}

当您不确定是否应该使用for...offor own...of时,通常使用 更安全own

于 2011-04-22T17:41:32.667 回答
2

您可以使用for x in yfor x of y取决于您希望如何解释元素列表。最新版本的 CoffeeScript 旨在解决这个问题,您可以在 GitHub 上阅读有关它的新用途和问题(此后已实施并关闭)

于 2011-04-22T03:48:07.453 回答