Javascript / jQuery - 定义时“无法调用未定义的'push'方法”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11882650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript/jQuery - "Cannot call method 'push' of undefined" while it IS defined
提问by Galadre
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:
但是现在我添加了另一个数组,在这种情况下,它应该只是存储相同的 q1A 变量。但不知何故,我最终得到了一个“未捕获的类型错误”,指出该变量未定义!新的代码块是:
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.
我在控制台中记录了变量,它工作得很好,它被设置并有一个值。知道为什么它说它未定义吗?'answers' 数组存储值就好了。
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();
采纳答案by Aaron Digulla
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
在您尝试调用push()
它时未定义。
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.
这个问题的常见原因是变量input
被声明在另一个地方,并且它从未在意想不到的地方初始化。
回答by Konga Raju
First you have to define as array.
首先你必须定义为数组。
var input=[];
then try to push the element.
然后尝试推动元素。
input.push(element);