Emiliano Morghen
Emiliano Morghen

Reputation: 40

Bidimensional Array Uncaught TypeError: Cannot set property '0' of undefined

I need to animate some circle in my page, in order to do that, i'm trying to store that circle in a matrix.

var elementWidth = parseInt($('#svg').width()); //Take container element's width
var circleRadius = parseInt(elementWidth/10); //Calculate radius and the distance from a circle to another
var circleMatrix = [[]]; //The 2d matrix
var s = Snap("#svg"); //Initialize Snap (it's a svg framework)
var x,y=0; //My index

for(var i=0; i<=elementWidth; i+=circleRadius){
  x=0;
  for(var m=0; m<=elementWidth; m+=circleRadius){
    console.log("y("+y+"): "+i+" x("+x+"): "+m);
    circleMatrix[y][x] = s.circle(m,i,50);
    x++;
  }
  y++;
}

The code is really easy and a i can't understand why it returns this error:

Uncaught TypeError: Cannot set property '0' of undefined

Upvotes: 1

Views: 5745

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074248

JavaScript doesn't really have two-dimensional arrays; it has arrays of arrays instead.

This line:

var circleMatrix = [[]]; //The 2d matrix

creates an array with one entry: A blank array. So circleMatrix[1] (for instance) is undefined.

You'll have to add arrays at all of the positions in the outer array for which you need them. One way to do that would be to add:

if (!circleMatrix[y]) {
    circleMatrix[y] = [];
}

just before this line:

circleMatrix[y][x] = s.circle(m,i,50);

E.g.:

var elementWidth = parseInt($('#svg').width()); //Take container element's width
var circleRadius = parseInt(elementWidth/10); //Calculate radius and the distance from a circle to another
var circleMatrix = [];                      // *** Changed
var s = Snap("#svg"); //Initialize Snap (it's a svg framework)
var x,y=0; //My index

for(var i=0; i<=elementWidth; i+=circleRadius){
  x=0;
  for(var m=0; m<=elementWidth; m+=circleRadius){
    console.log("y("+y+"): "+i+" x("+x+"): "+m);
    if (!circleMatrix[y]) {                 // *** Added
        circleMatrix[y] = [];               // *** Added
    }                                       // *** Added
    circleMatrix[y][x] = s.circle(m,i,50);
    x++;
  }
  y++;
}

Upvotes: 7

user1329482
user1329482

Reputation: 569

To create a 2D matrix in JavaScript, you have to do something like the following:

var circleMatrix = [[],[],[]];

You have to know ahead of time what one dimension is, or plan to create each "row" as you iterate the outer loop.

Upvotes: 0

Related Questions