Javascript/jQuery-“无法调用未定义的方法'push'"虽然它是定义的 [英] Javascript/jQuery - "Cannot call method 'push' of undefined" while it IS defined

查看:369
本文介绍了Javascript/jQuery-“无法调用未定义的方法'push'"虽然它是定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个简单的脚本中,它通过一些表单字段,获取用户输入并将其存储到数组中,我遇到了问题.

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);

但是现在我添加了另一个数组,在这种情况下,该数组应该简单地存储相同的q1A变量.但是不知何故,我最终得到了一个未捕获的TypeError",指出该变量是未定义的!新的代码块是:

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.

提前谢谢!

我当然定义了变量.我只是没有发布那部分代码...

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();

推荐答案

由于可以将未定义的变量无错误地推入数组,因此问题必须是在尝试调用input >.

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.

此问题的通常原因是,在另一个地方声明了变量input,并且从未在意外的地方对其进行初始化.

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.

这篇关于Javascript/jQuery-“无法调用未定义的方法'push'"虽然它是定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆