bestprogrammerintheworld
bestprogrammerintheworld

Reputation: 5520

Why do i get undefined when creating an multidimesional array in jquery (javascript)?

I want to create a multidimensional array and loop through it. I know it's possible because I've read about it, but I still can't figure why this does not work...

var bundeslan = [
    ["city1"][19161],
    ["city2"][19162],
    ["city3"][19162]
];

console.log(bundeslan);     

I want to associate each city with a number and use that number to identify a div.

My thought was to loop through the array like this...

//Start main loop
 $.each(bundeslan, function( key, value ) {

     //Inner loop
     $.each(key, function(innerKey, innerValue){
         alert(innerValue);
     });

 });

But why do I gut like [undefined][undefined][undefined] etc... in console.log(bundeslan)?

Upvotes: 1

Views: 24

Answers (3)

Sridhar Narasimhan
Sridhar Narasimhan

Reputation: 2653

Multidimentional array should be somewhat look like this

var items = [[1,2],[3,4],[5,6]];

Where as your code block looks wrong.

var bundeslan = [
[["city1"],[19161]],
[["city2"],[19162]],
[["city3"],[19162]]

];

console.log(bundeslan);

Upvotes: 0

Bhargav Ponnapalli
Bhargav Ponnapalli

Reputation: 9412

There is a syntax error. Do this.

var bundeslan = [
    [["city1"],[19161]],
    [["city2"],[19162]],
    [["city3"],[19162]]
];

And this will give you the desired result

$.each(bundeslan, function( key, value ) {
     //Inner loop
     console.log(value[1][0]);

 });

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

The syntax of your array definition is not quite correct, try this:

var bundeslan = [
    ["city1", 19161],
    ["city2", 19162],
    ["city3", 19162]
];    
console.log(bundeslan);  

I would also advise against the use of 2 dimensional arrays. If you want an associative array, use an object:

var bundeslan = {
    city1: 19161,
    city2: 19162,
    city3: 19162
};    
console.log(bundeslan);

Upvotes: 1

Related Questions