32

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
  • 10,448
  • 17
  • 59
  • 92

4 Answers4

16

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-
  • 209,133
  • 54
  • 439
  • 449
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
  • 8,787
  • 6
  • 29
  • 45
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
  • 376,738
  • 64
  • 519
  • 520
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-
  • 209,133
  • 54
  • 439
  • 449
Mritunjay
  • 24,184
  • 7
  • 51
  • 67