JavaScript可能的意外迭代 [英] JavaScript Possible Iteration Over Unexpected
问题描述
我有以下代码:
for (i in awards) {
if (awards[i] instanceof Array === false) {
console.log(awards[i]);
httpFactory.patch(awards[i], {"read": true}, false);
}
}
我的IDE显示与上述代码相关的错误:
My IDE shows this error relating to the code above:
对意外(自定义/继承)成员的可能迭代,
可能缺少hasOwnProperty检查
Possible iteration over unexpected (custom / inherited) members, probably missing hasOwnProperty check
检查JavaScript中未过滤的for-in循环的任何实例。
使用此构造会导致处理继承或意外的
属性。您需要使用hasOwnProperty()
方法过滤自己的属性。验证适用于JavaScript,html或jsp文件。
Checks for any instances of unfiltered for-in loops in JavaScript. The use of this construct results in processing inherited or unexpected properties. You need to filter own properties with hasOwnProperty() method. The validation works in JavaScript, html or jsp files.
您能否更详细地解释此声明的含义?
Could you explain in more detail what is meant by this statement?
推荐答案
IDE建议您添加测试:
The IDE is recommending that you add a test:
if (awards.hasOwnProperty(i)) {
...
}
在内
循环。
我个人建议不要这样做,并禁用尽可能警告。在大多数代码中根本不需要,甚至更少需要ES5代码,您可以使用 Object.defineProperty
I personally recommend not doing this, and disabling the warning if possible. There's simply no need in most code, and even less need in ES5 code where you can safely add non-enumerable properties to an object using Object.defineProperty
hasOwnProperty
只有在您向 Object.prototype Object.prototype添加不安全的新(可枚举)属性时才需要检查code>,所以最简单的修复是不要那样做。
The hasOwnProperty
check is only necessary if you have unsafely added new (enumerable) properties to Object.prototype
, so the simplest fix is don't do that.
jQuery不执行此测试 - 他们明确记录如果 Object.prototype
被不安全地修改,jQuery将会中断。
jQuery doesn't perform this test - they explicitly document that jQuery will break if Object.prototype
is unsafely modified.
这篇关于JavaScript可能的意外迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!