lilithbx
lilithbx

Reputation: 9

How to define a multidimensional array when is undefined?

This is my code:

    if(notas_insert[selected_n_document] === "undefined"){
        notas_insert[selected_n_document] = [];
    }
    if(notas_insert[selected_n_document][selected_version] === "undefined"){
        notas_insert[selected_n_document][selected_version] = [];
    }
    if(notas_insert[selected_n_document][selected_version]["index"] === "undefined"){
    notas_insert[selected_n_document][selected_version]["index"] = 0;
    }
    notas_insert[selected_n_document][selected_version][notas_insert[selected_n_document][selected_version]["index"]] = notas_pre;
    notas_insert[selected_n_document][selected_version]["index"]++;

I get this error:

Cannot read property '1' of undefined

How can I create an array within an array with code, because If I write in the console:

notas_insert[selected_n_document] = [];

I no longer get the error on the third line, but for some reason it doesn't seem to work if I do it within the code.

Upvotes: 0

Views: 29

Answers (2)

Tim
Tim

Reputation: 766

I'd set up defaults with something like this:

var doc = notas_insert[selected_n_document] || [];
var version = doc[selected_version] || [];

etc

Upvotes: 0

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Check your condition like this

if(typeof notas_insert[selected_n_document][selected_version] === "undefined")

Upvotes: 1

Related Questions