简体   繁体   中英

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 ai can't understand why it returns this error:

Uncaught TypeError: Cannot set property '0' of undefined

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

Eg:

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++;
}

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.

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