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.
This is because console. log() does not return a value (i.e. returns undefined). The result of whatever you entered to the console is first printed to the console, then a bit later the message from console. log reaches the console and is printed as well.
A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
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()); }); });
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()); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With