0

This is what I have:

function get_bad_changelist_authors() {
   var changelistAuthorDivs = $('div.bad_changelist_author');
   var changelistAuthors = [];

   for (var div in changelistAuthorDivs) {
      changelistAuthors.push($(changelistAuthorDivs[div]).text());
   }

   return changelistAuthors;
}

changeListAuthorDivs has n elements but for some reason it iterates n+1 times and initialized div to a string (ie. the string "length") on the last iteration. On the last iteration is where this loop has its error.

3
  • Already tried using a for loop with an explicit indexer? Like for(var i=0;i<list.length;i++) Commented Aug 16, 2011 at 7:57
  • Why not .each? Commented Aug 16, 2011 at 8:02
  • lol, i was just seriously confused about how div ="length...i find that a strange concept Commented Aug 16, 2011 at 8:07

3 Answers 3

2

It seems you are using jQuery (please confirm). Then you can use .map() [docs] to achieve the same in a more concise way:

function get_bad_changelist_authors() {
   return $('div.bad_changelist_author').map(function() {
        return $(this).text();
   }).get();
}

Alternatively , use .each() [docs] if you deal with jQuery objects.

In general, @James is completely right, don't use for...in to iterate over arrays (see the warning here). In this case, the jQuery object has to be treated like an array.

Sign up to request clarification or add additional context in comments.

2 Comments

Sweet, I think I'll try the map function out. And thanks for pointing out a resource where I can checkup Javascript documentation.
@Nadir: You are welcome. The jQuery documentation and the Mozilla JavaScript reference and guide are really great. I suggest to read the guide, it will give you some more insight into JavaScript. Happy coding! :)
1

JavaScript for...in loops will also iterate over properties of the object (length is a property of the object, which is why you end up with a div containing that string), which is not what you want. Use a normal for loop instead:

for(var i = 0; i < changeListAuthorDivs.length; i++) {
   //Do stuff
}

Comments

0

Try this

 for (var div in changelistAuthorDivs) {
     if(Object.prototype.hasOwnProperty.call(changelistAuthorDivs[div], div))
     changelistAuthors.push($(changelistAuthorDivs[div]).text());
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.