Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery - "Cannot call method 'push' of undefined" while it IS defined

In a simple script that goes through some form fields, gets the user input and stores it into arrays I ran into a problem.

It works when I do this:

var q1A = parseFloat($('#q1-1').val());
if(isNaN(q1A)) {
    var q1A = 0;
}
parameter.push(' ');
answers.push(q1A);

But now I added another array which, in this case, is supposed to simply store the same q1A variable. But somehow I end up with an "Uncaught TypeError" stating that the variable is undefined! The new code block is:

var q1A = parseFloat($('#q1-1').val());
if(isNaN(q1A)) {
    var q1A = 0;
}
input.push(q1A);
parameter.push(' ');
answers.push(q1A);

I logged the variable in the console and it works just fine, it's set and has a value. Any idea why it says it's undefined? The 'answers' array stores the value just fine.

Thanks in advance!

EDIT:

Of course I defined the variables. I just didn't post that part of the code...

var groups = new Array();
var questions = new Array();
var input = new Array();
var parameter = new Array();
var answers = new Array();
var amounts = new Array();
like image 483
Galadre Avatar asked Jan 16 '23 21:01

Galadre


2 Answers

Since it's possible to push an undefined variable into an array without error, the problem must be that input isn't defined when you try to call push() on it.

The usual reason for this problem is that there is another place where the variable input is declared and it's never initialized in the unexpected place.

like image 61
Aaron Digulla Avatar answered Jan 18 '23 11:01

Aaron Digulla


First you have to define as array.

var   input=[];

then try to push the element.

input.push(element); 
like image 31
kongaraju Avatar answered Jan 18 '23 10:01

kongaraju