I have the following object:
var r = {
obj: $(this),
children: $(this).children(),
panes: $('.rotatorPane', $(this)),
tagNames : [],
captions: [],
subcaptions: []
};
$(this) refers to the following div:
<div class="myRotator">
<div class="rotatorPane">
</div>
<div class="rotatorPane" id="pane3">
</div>
<img src="img/1.jpg" alt="pane 1" class="rotatorPane" data-caption="Lorem Ipsum" data-subcaption="Dolor sit amet" />
</div>
The problem I’m having is with the following for…in loop:
for(pane in r.panes){
console.log(pane);
}
The output starts out as expected:
0
1
2
But then I get a bunch of method names as outputs:
length
prevObject
context
selector
constructor
init
jquery
size
toArray
get
...etc
Does anyone know why this is happening?
Don’t use
for ... inon things that are arrays, or array-like. Use a numeric index variable.The
for ... inform is for iterating over the properties of an object — all of them. When you want to iterate through the indexed properties of an array (or, again, something that you’re treating as an array), always use a numeric index.In this case, the array-like object in question is a jQuery object, which has all sorts of properties besides the numerically-indexed properties.