views:

291

answers:

2

I got this error and dont know what could be the cause. Any idea?

Problem at line 2127 character 18: Bad for in variable 'sport'. for (sport in sugested_sports)

                // make array
        var sugested_sports = data.split(",");

            // pre build DIV
        var sporty_items = '';
        for (sport in sugested_sports)
        {
            if  (sugested_sports.hasOwnProperty(sport)) {
                sporty_items += '<a href="#'+identifier[1]+'">'+sugested_sports[sport]+'</a>';
            }
        }
            // insert DIV
        DIVsuggestions.html(sporty_items);

thx alot.

+4  A: 

Try

for (var sport in sugested_sports)
Pointy
thx, how stupid ;-)
Marcel
+4  A: 

Pointy's answer is probably the one that lint is complaining about.


As a general rule you though, you should be careful when using for (... in ...). People often confuse this construct with foreach from C#, or other similar concepts in other languages, when in fact it isn't related. The javascript for in construct iterates every member of the object -- rather than just values in a collection -- including methods and properties. This behaviour can often lead to unexpected side effects if you aren't aware of how it works beforehand.

For example:

x = ['one', 'two'];
for (var value in x) {
  alert(value);
}

That yields two alerts, the first contaning 0 and the second 1, notably the indexes of the collection.

If we change that up a bit:

x = ['one', 'two'];
x.method = function() {};
for (var value in x) {
  alert(value);
}

We end up with three alerts this time, 0, 1, and method. This is the unexpected behaviour I was referring to. It's fine to use in if you know what it does, but I've seen it catch people out on more than one occasion.

The following works with both examples:

x = ['one', 'two'];
for (var i = 0; i < x.length; i++) {
  alert(i);
}
James Gregory
+1 Couldn't agree more, in addition, the order of iteration is not guaranteed by the [language specification](http://bclary.com/2004/11/07/#a-12.6.4), the properties (array indexes) may not visited in the numeric order, and also, if the `Array.prototype` object is extended (like [some libraries](http://mootools.net/docs/core/Native/Array) still do), those properties will be also enumerated...
CMS