Kai23
Kai23

Reputation: 1576

Multidimensional array in Javascript: Cannot set property '0' of undefined

I'm trying to build an array of strings, but I got an

Uncaught TypeError: Cannot set property '0' of undefined

I don't really get why, here is my code.

$("#tableLits > tbody > tr input").filter(function(){ return $(this).val() !== '' }).each(function(){
    nom = $(this).attr('name');
    numChambre = parseInt(nom.charAt(nom.length-1));
    taille = nom.slice(nom.charAt(nom.length-2),-2).replace('lit','');          
    chambres[numChambre][nbLits] = taille;              
    nbLits = oldChambre == numChambre ? nbLits++ : 0;
    oldChambre = numChambre;
});
console.log(chambres);

The error is on this line:

chambres[numChambre][nbLits] = taille;  

But when I look at the debugger,

My goal is to assign a size of a bed (taille) to a bed number (nbLit) in a given room (chambres)

Edit

For example, I have this: lit80n1 lit90n1 lit120n2 lit160n3

And I want to output something like this:

Chambre 1 -> 1 bed : 80cm, 1 bed : 90cm
Chambre 2 -> 1 bed : 120 cm
Chambre 3 -> 1 bed : 160cm

Upvotes: 0

Views: 1263

Answers (2)

VisioN
VisioN

Reputation: 145478

Before adding elements to the second dimension of the array you need to define it:

chambres[numChambre] = [];
chambres[numChambre][nbLits] = taille; 

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 817238

JavaScript does not have multi-dimensional arrays. What you can have is an array of arrays, but you have to initialise each "sub-array" explicitly:

if (!chambres[numChambre]) {
    chambres[numChambre] = [];
}
chambres[numChambre][nbLits] = taille; 

Upvotes: 4

Related Questions