16 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
}
}
Run Code Online (Sandbox Code Playgroud)
使用尽可能少的Javascript是很好的...有关如何实现这一点以及最大限度地使用Coffeescript的任何建议?
Ale*_*yne 16
for item in items您可以使用for attr, value of object,而不是通过数组进行迭代,而更像for inJS.
for own attr, value of this
if attr == 'foo' && value == 'bar'
console.log 'Found a foobar!'
Run Code Online (Sandbox Code Playgroud)
编译:https://gist.github.com/62860f0c07d60320151c
它接受循环中的键和值,非常方便.并且您可以在own紧接着之后插入关键字for,以便强制执行if object.hasOwnProperty(attr)检查,该检查应该过滤掉您不想要的原型中的任何内容.
Squeegy的答案是正确的.让我修改一下,通过添加JavaScript的for...in"危险"(通过包含原型属性)的常用解决方案是添加一个hasOwnProperty检查.CoffeeScript可以使用特殊own关键字自动执行此操作:
for own attr of this
...
Run Code Online (Sandbox Code Playgroud)
相当于JavaScript
for (attr in this) {
if (!Object.prototype.hasOwnProperty(this, attr)) continue;
...
}
Run Code Online (Sandbox Code Playgroud)
如果对是否应该使用for...of或存在疑问for own...of,通常使用起来更安全own.
| 归档时间: |
|
| 查看次数: |
4140 次 |
| 最近记录: |