简体   繁体   中英

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?

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM