I have some javascript as shown below
for (var titleKey in data.d) {
var title = data.d[titleKey];
}
This is actually coming back from a JQuery call to a .NET webservice but I don’t believe that’s related.
My loop iterates over each element in the collection correctly, it then continues through the loop one more time. The titleKey here is ‘indexof’ and title is ‘undefined’.
This is happening in two different places in my code.
What is causing this? How can I prevent it?
Thanks in advance.
You need to exclude from the loop the properties of the prototype. The
for ... instructure will loop through everything* it finds in the prototype chain, not only the properties of the child object.From what the console log says my suspicion is that you have a library that implements the
indexoffor Array in its prototype.My recommendation would be to use the correct way to walk Arrays:
for inis for Objects, not Arrays. This is a common beginner mistake, where one abuses the fact that Array is derived from Object.*See comment from davidchambers