Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'push' of undefined when combining arrays

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!

like image 612
d3nm4k Avatar asked Jul 19 '14 14:07

d3nm4k


People also ask

What does Cannot read property of undefined mean?

What Causes TypeError: Cannot Read Property of Undefined. Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects.

Can't access property push history is undefined?

To fix the "Cannot read property 'push' of undefined" error with React Router, we should call the withRouter component with our route component so the history object is available in the props. import { withRouter } from "react-router"; class App extends Component { push = () => { this. props. history.


2 Answers

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

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.

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]; } } 
like image 186
Pointy Avatar answered Sep 20 '22 07:09

Pointy


This error occurs in angular when you didn't intialise the array blank.
For an example:

userlist: any[ ]; this.userlist = [ ];  

or

userlist: any = [ ]; 
like image 27
Yogesh Aggarwal Avatar answered Sep 20 '22 07:09

Yogesh Aggarwal