0

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,

  • Chambre is an array
  • numChambre = 1
  • nbLit = 0

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

2 Answers 2

4

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

5 Comments

@VisioN: If you want to be explicit, yes (though personally I'd prefer typeof). But I think in a controlled environment, this would be sufficient.
Agree, and let's hope that chambres[numChambre] will never become falsy.
Thansk for the answer. It almost works, the « problem » is that it overwrite my first « nbLit ». So, instead of 4 elements, I have 3 arrays with only one element in the inside.
@Kai23: The values for numChambre and nbLits might not be what you expect or this might not be the right approach to create the data structure you want, I don't know. Read this to learn how to debug JavaScript and inspect your code and variables.
Just had to do this : nbLits = (oldChambre == numChambre) ? nbLits + 1 : 0;
1

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

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

Comments

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.