执行一个foreach在关联数组的关联数组

执行一个foreach在关联数组的关联数组

本文介绍了执行一个foreach在关联数组的关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的设置:

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

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

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?

推荐答案

使用对象而不是数组。

var whatever = {};

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

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

这篇关于执行一个foreach在关联数组的关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:52