组合数组时无法读取未定义的属性'push' [英] Cannot read property 'push' of undefined when combining arrays
问题描述
当将数组的内容推送到另一个数组时,我得到
When pushing an array's contents to another array I get
未捕获的TypeError:无法读取未定义的属性'push'错误
在此代码段中。
"Uncaught TypeError: Cannot read property 'push' of undefined" error in this snippet.
var order = new Object(), stack = [];
for(var i=0;i<a.length;i++){
if(parseInt(a[i].daysleft) == 0){ order[0].push(a[i]); }
if(parseInt(a[i].daysleft) > 0){ order[1].push(a[i]); }
if(parseInt(a[i].daysleft) < 0){ order[2].push(a[i]); }
}
为什么我会在第二个中出现此错误> 强烈的声明?
非常感谢!
Why do I get this error in the second if statement ? Thanks a lot!
推荐答案
您收到错误,因为 order [1]
是 undefined
。
You get the error because order[1]
is undefined
.
该错误消息意味着代码中的某处,正在尝试访问具有某个名称的属性(此处为push),而不是对象,引用的基础实际上是 undefined
。因此,要找到问题,您需要查找引用该属性名称(push)的代码,并查看其左侧的内容。在这种情况下,代码是
That error message means that somewhere in your code, an attempt is being made to access a property with some name (here it's "push"), but instead of an object, the base for the reference is actually undefined
. Thus, to find the problem, you'd look for code that refers to that property name ("push"), and see what's to the left of it. In this case, the code is
if(parseInt(a[i].daysleft) > 0){ order[1].push(a[i]); }
这意味着代码需要 order [1]
成为一个数组。但是,不是一个数组;它是 undefined
,所以你得到错误。为什么未定义
?好吧,根据您提出的问题,您的代码无法做任何事情。
which means that the code expects order[1]
to be an array. It is, however, not an array; it's undefined
, so you get the error. Why is it undefined
? Well, your code doesn't do anything to make it anything else, based on what's in your question.
现在,如果您只想放置 a [i]
在对象的特定属性中,然后根本不需要调用 .push()
:
Now, if you just want to place a[i]
in a particular property of the object, then there's no need to call .push()
at all:
var order = [], stack = [];
for(var i=0;i<a.length;i++){
if(parseInt(a[i].daysleft) == 0){ order[0] = a[i]; }
if(parseInt(a[i].daysleft) > 0){ order[1] = a[i]; }
if(parseInt(a[i].daysleft) < 0){ order[2] = a[i]; }
}
这篇关于组合数组时无法读取未定义的属性'push'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!