在关联数组的关联数组上执行foreach

时间:2012-02-14 00:11:40

标签: javascript jquery arrays

假设我有这个设置:

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

我试图迭代它:

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

然而迭代失败了,注释掉嵌套的foreach循环将允许页面加载,所以这似乎是问题所在。

在第一个循环中,我可以执行以下操作:

alert(value["a"]);

并获得正确的值,因此它似乎是一个“有效”的数组。我哪里出错,因为嵌套循环与外层循环基本相同?

1 个答案:

答案 0 :(得分:3)

使用对象而不是数组。

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/