33

Here is my code:

var textArray = ['#text1', '#text2', '#text3', '#text4',
'#text5', '#text6', '#text7', '#text8']

$('#capture').click(function() {
    for (var i in textArray) {
      console.log($(i).offset());
    }
});

Not sure why I am getting undefined in console. I feel like I am missing something very simple.

metersk
  • 11,803
  • 21
  • 63
  • 100

4 Answers4

17

A for…in loop in JavaScript loops through an object’s keys, not its values. You can use Array.prototype.forEach, given support; $.each works as a fallback too, since you’re using jQuery.

var textArray = ['#text1', '#text2', '#text3', '#text4',
                 '#text5', '#text6', '#text7', '#text8'];

$('#capture').click(function() {
    textArray.forEach(function (x) {
        console.log($(x).offset());
    });
});
Ry-
  • 218,210
  • 55
  • 464
  • 476
2

You probably want to index off the array like this:

var textArray = ['#text1', '#text2', '#text3', '#text4',
'#text5', '#text6', '#text7', '#text8']

$('#capture').click(function() {
for (var i in textArray) {
  console.log($(textArray[i]).offset());
}
});
therealrootuser
  • 10,215
  • 7
  • 31
  • 46
0

Because i is the index of the item in array, you need to use textArray[i] to access the current item(if you had logged the value of i it would show 0,1,2...7).

for (var i in textArray) {
  console.log($(textArray[i]).offset());
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You should not loop over an array using for..in. That is meant to loop over an Object {}

Use below

$('#capture').click(function() {
    $.each(textArray, function(value) {
        console.log($(value).offset());
    })
});

You can use Array#forEach, but IE8 doesn’t support forEach, so I did it using jQuery’s each.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Mritunjay
  • 25,338
  • 7
  • 55
  • 68