1

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)?

1
  • 1
    "I want to associate each city with a number" Sounds like you should be using an object instead of an array: {"city1": 19161, "city2": 19162, "city3": 19162} Commented Oct 12, 2015 at 9:52

3 Answers 3

2

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

2 Comments

Note that this gives you a nested array three levels deep, each containing a single value. I don't think this is exactly what the OP is after.
Yeah, @RoryMcCrossan's method makes more sense though. However, if you insist on a multi dimensional array then this would be the way to go.
1

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); 

2 Comments

Thank you. This seems to make more sense in my case.
No problem, glad to help.
0

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); 

1 Comment

When doing like this I didn't get a multidimensional array. Just an array with a comma after the the city.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.