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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With