javascript – Cannot read property push of undefined when combining arrays
javascript – Cannot read property push of undefined when combining arrays
You get the error because order[1]
is undefined
.
That error message means that somewhere in your code, an attempt is being made to access a property with some name (here its push), but instead of an object, the base for the reference is actually undefined
. Thus, to find the problem, youd look for code that refers to that property name (push), and see whats to the left of it. In this case, the code is
if(parseInt(a[i].daysleft) > 0){ order[1].push(a[i]); }
which means that the code expects order[1]
to be an array. It is, however, not an array; its undefined
, so you get the error. Why is it undefined
? Well, your code doesnt do anything to make it anything else, based on whats in your question.
Now, if you just want to place a[i]
in a particular property of the object, then theres 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]; }
}
This error occurs in angular when you didnt intialise the array blank.
For an example:
userlist: any[ ];
this.userlist = [ ];
or
userlist: any = [ ];
javascript – Cannot read property push of undefined when combining arrays
order
is an Object
, not an Array()
.
push()
is for arrays.
Refer to this post
Try this though(but your subobjects have to be Arrays()
):
var order = new Array();
// initialize order; n = index
order[n] = new Array();
// and then you can perform push()
order[n].push(some_value);
Or you can just use order as an array of non-array objects:
var order = new Array();
order.push(a[n]);