-1

In a for loop, the i is my loop counter.

console.log($(f_images[i].DOM));

$(f_images[i].DOM).hover(function() {
    console.log($(f_images[i].DOM));
}, function() {});

Console showed me:

[object Object]
"Uncaught TypeError: Cannot read property 'DOM' of undefined". 

Same thing happened if I replace $(f_images[i].DOM) with whatever related to f_images.

Why can't I access the object array itself in the hover function?

Rodrigo Taboada
  • 2,727
  • 4
  • 24
  • 27
yang
  • 27
  • 4
  • Is this in a loop? Is `i` your loop counter? – Alex Wayne Feb 05 '15 at 00:14
  • sorry i forgot to mention it's in a for loop. – yang Feb 05 '15 at 00:15
  • 1
    Impossible to tell why that happens other than the `DOM` property is missing from some (or all) of your `f_images` elements. – Ja͢ck Feb 05 '15 at 00:17
  • Read that message carefully... It's not that `DOM` is undefined on the objects, it's that `f_images[i]` is returning `undefined`, which raises an exception when you try to access a property of `undefined`. – Alex Wayne Feb 05 '15 at 00:26

2 Answers2

1

You basically have this problem: JavaScript closure inside loops – simple practical example

By the time your hover function runs, i is the last value that would end the loop, the first index out of range.

Use a closure to close over i in your loop as described in that answer and it should work as you expect.

for (var i = 0; i < f_images.length; i++) {
  (function(i) {
    $(f_images[i].DOM).hover(function(){
      console.log($(f_images[i].DOM));
    }, function(){

    });
  }(i));
}
Community
  • 1
  • 1
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
-1

replace

$(f_images[i].DOM)

with:

$('f_images' + [i] + '.DOM')
arnolds
  • 778
  • 6
  • 12
  • `$('f_images' + [i] + '.DOM')` makes no sense here. A jQuery selector cannot be used to read local variables like what `f_images` seems to be. – Alex Wayne Feb 05 '15 at 00:24