wchristiansen
wchristiansen

Reputation: 436

JavaScript 2D Array Uncaught TypeError

Working on a project where I need to add points to an array. Here is the code for creating and then trying to add an object to the array:

var points = [];
    points[0] = [];
    points[0][0] = 0; //x-coord
    points[0][1] = 0; //y-coord

points[points.length][0] = x; //Breaks on this line
points[points.length][1] = y;

The exact error I get is Uncaught TypeError: Cannot set property '0' of undefined. This code is run every time a button is pressed and the other values are already ints that are set. I thought that JavaScript allowed you to set values in arrays as you go?

Upvotes: 0

Views: 943

Answers (2)

Joseph
Joseph

Reputation: 119827

your array contains:

var points = [
    [0,0]
]

However

points[points.length]
//is
points[1]

which does not exist. you must create the array first, before you actually add stuff to it

Here's a sample

var length = points.length;  //cache value, since length is "live"
points[length] = [];         //using the cached length, create new array
points[length][0] = x;       //add values
points[length][1] = y;

Upvotes: 1

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

The last array index is points.length - 1. Now you are addressing an element past the end of array (which is undefined) and trying to assign its "0" property a value of x. Setting properties on undefined is not allowed.

Upvotes: 2

Related Questions