When pushing an array's contents to another array I get
"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!
This question is related to
javascript
jquery
web
console
answer to your question is simple order is not a object make it an array. var order = new Array(); order.push(/item to push/); when ever this error appears just check the left of which property the error is in this case it is push which is order[] so it is undefined.
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]);
This error occurs in angular when you didn't intialise the array blank.
For an example:
userlist: any[ ];
this.userlist = [ ];
or
userlist: any = [ ];
Generally, Push method is used to add elements at the end of an array.
Here, you have used the push method to an object and not an array which is 'order'.
Steps to debug...
Change the object into an empty array,
var order = [], stack = [];
Now you can use the push method for this array as usual.
To use push method to this 'order' array; you should not use the array index when calling push method to an array. Just use the name of the array only.
var order = [], stack = [];
for(var i = 0; i<a.length; i++){
if(parseInt(a[i].daysleft) == 0){
order.push(a[i]);
}
if(parseInt(a[i].daysleft) > 0){
order.push(a[i]);
}
if(parseInt(a[i].daysleft) < 0){
order.push(a[i]);
}
}
In most cases you have to initialize the array,
let list: number[] = [];
I fixed in the below way with typescript
pageNumbers: number[] = [];
than populate it
for (let i = 1; i < 201; i++) {
this.pageNumbers.push(i);
}
You do not need to give an index.
Instead of doing order[0].push(a[i])
, just do order.push(a[i])
.
order[] is undefined that's why
Just define order[1]...[n] to = some value
this should fix it
Source: Stackoverflow.com