1

I am iterating over a JSON array (rec'd from a webworker AJAX call)

var dataReceived = JSON.parse(xhr.responseText);//JSON verified as ok
                                               //dataReceived.length verified 
    var dataProcessed = []; 
   for (var i = 0; i < dataReceived.length; i++) {
    for ( var h = 0; h < dataReceived[i].length; h++) {
                dataProcessed[i][h][0]=((dataReceived[i][h][0])*30)-30;
                dataProcessed[i][h][1]=((dataReceived[i][h][1])*30)-30;
        }
    }
    postMessage(dataProcessed);

But i get the error

dataProcessed[i] is undefined

Does Javascript not create multidimensional arrays on the fly?

EnglishAdam
  • 1,380
  • 1
  • 19
  • 42

2 Answers2

7

Does Javascript not create multidimensional arrays on the fly?

No, you have to create it:

for (var i = 0; i < dataReceived.length; i++) {
    dataProcessed[i] = [];        // <============= Here
    for ( var h = 0; h < dataReceived[i].length; h++) {
        dataProcessed[i][h] = []; // <============= And here

Side note: You can make that more efficient by factoring out your repeated lookups; also, you can create and initialize the innermost array simultaneously:

var dataReceived = JSON.parse(xhr.responseText);
var dataProcessed = []; 
var recEntry, procEntry;
for (var i = 0; i < dataReceived.length; i++) {
    procEntry = dataProcessed[i] = [];
    recEntry = dataReceived[i];
    for ( var h = 0; h < recEntry.length; h++) {
        procEntry[h] = [
            ((recEntry[h][0])*30)-30,
            ((recEntry[h][1])*30)-30
        ];
    }
}
postMessage(dataProcessed);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

No, javascript does not create multidimensional arrays on the fly. You will have to look for the edge case .e.g. first iteration of the loop, and then create an empty array.

Or you can also initialize the array using || operator

for (var i = 0; i < dataReceived.length; i++) {

dataProcessed[i] = []; // array

for ( var h = 0; h < dataReceived[i].length; h++) {
            dataProcessed[i][h] = []; // array
            dataProcessed[i][h][0]=((dataReceived[i][h][0])*30)-30;
            dataProcessed[i][h][1]=((dataReceived[i][h][1])*30)-30;
    }
}
postMessage(dataProcessed);
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175