3

Suppose I have this setup:

var whatever = new Array();

whatever["a"] = new Array();
whatever["a"]["a"] = "test1";
whatever["a"]["b"] = "test2";

whatever["b"] = new Array();
whatever["b"]["a"] = "test3";
whatever["b"]["b"] = "test4";

And I attempt to iterate through it:

$.each(whatever, function(key, value) {
 $.each(value, function(subkey, subvalue) {
  //stuff with key, subkey, and subvalue here
 });
});

Yet the iteration fails, commenting out the nested foreach loop will allow the page to load, so that appears to be where the problem is.

Inside the first loop, I can do something like:

alert(value["a"]);

and receive the proper value, so it seems to be a "valid" array. Where am I going wrong, since the nested loop is basically the same as the outer one?

user173342
  • 1,820
  • 1
  • 19
  • 45
  • What exactly are you trying to do with this? In most cases an object is a better idea than nested arrays. – elclanrs Feb 14 '12 at 00:14
  • Javascript arrays are never associative and cannot have strings as keys. Javascript arrays are numerically indexed. What you're looking for is an object, which is a key-value store. – deceze Feb 14 '12 at 00:14
  • @deceze javascript arrays are just objects with numerical strings as keys, that said it's still better to use an object... – Esailija Feb 14 '12 at 00:19
  • @Esailija Setting a string key on a Javascript Array object is not using the array properties of it. Yes, obviously you can do it, as the OP demonstrates, but it's not doing what you think. – deceze Feb 14 '12 at 00:21

1 Answers1

3

Use objects instead of arrays.

var whatever = {};

whatever["a"] = {};
whatever["a"]["a"] = "test1";
whatever["a"]["b"] = "test2";

whatever["b"] = {};
whatever["b"]["a"] = "test3";
whatever["b"]["b"] = "test4";

http://jsfiddle.net/QwT8W/