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?

2
  • Yes its three dimensional, no nulls Commented Feb 24, 2014 at 10:08
  • Question title changed Commented Feb 24, 2014 at 10:10

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, like your thinking about how to solve, +1 and will accept in a minute or too
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);

1 Comment

Thanks, changed the question title to help being found too, +1

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.