What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

后端 未结 8 863
长情又很酷
长情又很酷 2020-11-30 15:57

I used JSLint on a JavaScript file of mine. It threw the error:

for( ind in evtListeners ) {

Problem at line 41 character 9:

8条回答
  •  Happy的楠姐
    2020-11-30 16:40

    Surely it's a little extreme to say

    ...never use a for in loop to enumerate over an array. Never. Use good old for(var i = 0; i

    ?

    It is worth highlighting the section in the Douglas Crockford extract

    ...The second form should be used with objects...

    If you require an associative array ( aka hashtable / dictionary ) where keys are named instead of numerically indexed, you will have to implement this as an object, e.g. var myAssocArray = {key1: "value1", key2: "value2"...};.

    In this case myAssocArray.length will come up null (because this object doesn't have a 'length' property), and your i < myAssocArray.length won't get you very far. In addition to providing greater convenience, I would expect associative arrays to offer performance advantages in many situations, as the array keys can be useful properties (i.e. an array member's ID property or name), meaning you don't have to iterate through a lengthy array repeatedly evaluating if statements to find the array entry you're after.

    Anyway, thanks also for the explanation of the JSLint error messages, I will use the 'isOwnProperty' check now when interating through my myriad associative arrays!

提交回复
热议问题