Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting 'undefined' in console? [duplicate]

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.

like image 333
metersk Avatar asked Aug 20 '14 03:08

metersk


People also ask

Why does my console log say undefined?

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.

Why does Javascript console return undefined?

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 .


2 Answers

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());     }); }); 
like image 167
Ry- Avatar answered Sep 24 '22 14:09

Ry-


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()); } }); 
like image 24
therealrootuser Avatar answered Sep 25 '22 14:09

therealrootuser