Why am I getting "undefined" in the console?

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 the console. I feel like I am missing something very simple.

+3


source to share


4 answers


Cycle

A for…in

in JavaScript handles the keys of an object, not its values. You can use Array.prototype.forEach

, subject to support; $.each

also works as a fallback since you are using jQuery.



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

$('#capture').click(function() {
    textArray.forEach(function (x) {
        console.log($(x).offset());
    });
});

      

+8


source


Since i

is the index of the element in the array, you need to use textArray[i]

to access the current element (if you registered a value i

it will show 0,1,2 ... 7).



for (var i in textArray) {
  console.log($(textArray[i]).offset());
}

      

0


source


You probably want to index 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());
}
});

      

0


source


You don't have to iterate over the array with for..in

. This is for looping the 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 with jQuerys each

.

0


source







All Articles