In Javascript, I have a matrix with a variable number of rows and columns, which I wish to store in a multi-dimensional array.
The problem is that I need extra 3 columns and 3 extra rows with negative indexes in the matrix too. So the result for a 10×10 matrix should be a 13×13 array with indexes from -3 to 9.
I define the array with:
var numberofcolumns = 10;
var numberofrows = 10;
var matrix = [];
for (var x = -3; x < numberofcolumns; x++) {
matrix[x] = [];
}
Is this the right way to do this? Or is there a better way?
You could define the matrix as an object instead. You would lose some array functionality but you could still access
matrix[-3]for example.Or you could define your own class starting as an object or array and work from there. Here’s something to get you started:
Then you’d create your matrix as such
And you can run some cool functions on it
DEMO: http://jsfiddle.net/uTVUP/