Will this for-in loop detection snippet generate unwanted false positives?

后端 未结 1 1978
予麋鹿
予麋鹿 2021-02-04 18:13

We all know that for-in-loops on arrays are absolutely evil. Still, they are often used and the caused errors are complicated to trace down, especially when happening browser-de

1条回答
  •  悲哀的现实
    2021-02-04 18:54

    Yes. Legitimacy can often be subjective, but...

    As an example, perhaps I have a sparse array, where I have only set values at the indexes with data:

    var a = [];
    a[123123] = "foo";
    a[1233123] = "bar";
    

    If I wanted to iterate over the elements that I defined in this array, then I would use the for...in construct. Even if I coded it defensively, your script would still trigger (a false positive)...

    for (var prop in a) {
      if (a.hasOwnProperty(prop)) {
        // this is a legitimate array element
      }
    }
    

    See also Why is using "for...in" with array iteration a bad idea? for more information and opinions.

    0 讨论(0)
提交回复
热议问题