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.
source to share
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());
});
});
source to share
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
.
source to share