0

Let's say I got an object as follows:

function node(xVal, yVal, nodeType) {
    this.xVal = xVal; // x-coordinate of node
    this.yVal = yVal; // y-coordinate of node
    this.nodeType = nodeType; // node type - outside the scope of this question
}

In an attempt to create a series of nodes on a x-by-y virtual plane, I specified a two-dimensional array as follows:

var ROWS = 3; // number of rows in the array
var COLS = 10; // number of columns in the array
var Nodes = new Array(ROWS);

for (var i=0; i < ROWS; i++) {
    for (var j=0; j < COLS; j++) {
        Nodes[i][j] = new node(0, 0, "Type A");
    }
}

I was expecting the above embedded for-loop would allow me to initialize the 3x10 array, each with 'node' object but something appears to be causing an error. Any thoughts as to 1) what might be causing the error, and 2) how to improve the logic will be greatly appreciated!

1
  • Nodes[i] is not defined. You have to initialize it with a value first, i.e. the "second level" array. Commented Jun 22, 2013 at 20:09

2 Answers 2

1

It is causing an error because you did not initialize a new array on the first dimension. Try putting Nodes[i] = []; before your second loop.

Also, you don't have to initialize an Array like that. You can just du var Nodes = [];

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

2 Comments

Initializing it using the Array constructor is faster when dealing with large numbers.
Guess it depends on the browser, Chrome hasn't optimized for that case. Reserving the size of an array should be faster than constantly changing it.
0

You should define the inner array as well.

for (var i=0; i < ROWS; i++) {
    Nodes[i] = new Array(COLS);
    for (var j=0; j < COLS; j++) {
        Nodes[i][j] = new node(0, 0, "Type A");
    }
}

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.