JavaScript:JSLint 错误“for in 的主体应包含在 if 语句中,以从原型中过滤掉不需要的属性”
我正在使用 JSLint 工具来确保我的 JavaScript 是“严格的”。
我收到以下错误,但不明白如何修复它:
The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype
对于以下代码:
for (var i in keypairs) {
...
}
任何人都知道如何修复此错误,因为它是 JavaScript“严格”并且不会被 JSLint 标记
I'm using the JSLint tool to ensure my JavaScript is "strict".
I'm receiving the following error but don't understand how to fix it:
The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype
For the following code:
for (var i in keypairs) {
...
}
Anyone have any ideas how to fix this to that it's JavaScript "strict" and won't be flagged by JSLint
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果
keypairs
是一个数组,那么您应该真正迭代这些元素,例如:如果
keypairs
是一个散列,那么 JSLint 正确地建议您检查您是否正在操作适当的密钥类型(即,确认哈希是预期的类型),因此类似
if 验证任何标准的情况可确保您不会访问原型函数等。
If
keypairs
is an array, then you should really iterate over the elements like:If
keypairs
is a hash, then JSLint is correctly recommending that you check that you are operating on the appropriate key type (i.e., confirming that the hash is the expected type)so something like
where the if is validating whatever criteria ensures that you are not accessing a prototype function etc.
它希望您使用
hasOwnProperty
。与 JSLint 的大部分内容一样,这是一个建议,其适用性取决于您的情况。如果对象的原型中有不需要的可枚举属性,那么它很有用。例如,如果您使用某些 JavaScript 库,则可能会出现这种情况。
It wants you to use
hasOwnProperty
.Like much of JSLint, this is a recommendation, and its applicability depends on your situation. It is useful if there are undesired enumerable properties in the object's prototype. This might be the case if you e.g. use certain JavaScript libraries.
for...in
的问题是您还将遍历原型的属性,而大多数时候这不是您想要的。这就是为什么您应该使用hasOwnProperty
测试该属性:The problem with
for...in
is that you will also traverse the properties of the prototype and most of the time this is not what you want. That is why you should test the property withhasOwnProperty
:这是因为
for
/in
循环可能会迭代由第 3 方库扩展的某些方法,例如,如果存在没有
.hasOwnProperty() 条件下,
.clone
方法也会在...
中迭代。http://yuiblog.com/blog/2006 进一步解释了这一点/09/26/for-in-intrigue/,从 JSLint 页面本身链接。
您可以通过选中“容忍未过滤的内容”来关闭此警告。
This is because the
for
/in
loop may iterate over some method extended by 3rd party library, e.g. if there is athen without the
.hasOwnProperty()
condition, the.clone
method will be iterated in the...
as well.This is further explained in http://yuiblog.com/blog/2006/09/26/for-in-intrigue/, linked from the JSLint page itself.
You can turn off this warning by checking "Tolerate unfiltered for in".
看一下 jslint 自己的文档:
http://www.jslint.com/lint.html
跳到该部分
,
他们执行以下操作:
for (对象中的名称) { if (object.hasOwnProperty(name)) { .... } }
take a look at jslint's own documentation:
http://www.jslint.com/lint.html
jump down to the section
for in
they do the following:
for (name in object) { if (object.hasOwnProperty(name)) { .... } }