0

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?

1
  • I'd recommend using an array of objects instead: points = []; points[0] = {x: 0, y: 0}; Commented May 11, 2012 at 17:38

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, as soon as I posted, I realize I was initializing the second array and had to write a function to instantiate the inner arrays. Thanks for the prompt answer though!
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.