coffeescript - 如何在 Coffeescript 中使用 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 的任何建议?

最佳答案

而不是 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/

相关文章:

backbone.js - 如何使用 2 种不同的模型扩展 Backbone 模型

Javascript/Coffeescript 鼠标悬停函数 RoR

javascript - 想要获取的不是延迟对象而是数组

javascript - Rails 在 Bootstrap 4 模态中执行 Javascript

javascript - 如何将 Javascript/Coffeescript 整数数组传递到我的 Rails 应用程序?

javascript - 在 lodash.js 中,它会缓存 `.value()` 方法的结果吗?

javascript - 如何在文件上传完成时调用 JS 回调?

cakephp - Coffeescript 和 CakePHP

javascript - 将 `this` 传递给访问其属性的函数给出未定义?

javascript - d3 : Why does this function not remove elements?