问题
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
回答1:
If keypairs
is an array, then you should really iterate over the elements like:
for(var i = 0; i < keypairs.length; i++) {
...
}
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
for(var i in keypairs) {
if(keypairs.hasOwnProperty(i)) {
...
}
}
where the if is validating whatever criteria ensures that you are not accessing a prototype function etc.
回答2:
It wants you to use hasOwnProperty
.
for (var i in keypairs) {
if(keypairs.hasOwnProperty(i))
{
// Use i
}
}
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.
回答3:
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 with hasOwnProperty:
for (var i in keypairs) {
if(keypairs.hasOwnProperty(i) {
//...
}
}
回答4:
for (var i in keypairs) {
if (keypairs.hasOwnProperty(i)) {
...
}
}
This is because the for
/in
loop may iterate over some method extended by 3rd party library, e.g. if there is a
Object.prototype.clone = function() { ... }
then 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".
回答5:
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)) { .... } }
来源:https://stackoverflow.com/questions/4166551/javascript-jslint-error-the-body-of-a-for-in-should-be-wrapped-in-an-if-statem