【问题标题】:Looping through a multidimensional array with jQuery使用 jQuery 循环遍历多维数组
【发布时间】:2015-09-12 07:33:30
【问题描述】:

我正在尝试使用 jQuery 的 each 函数循环遍历下面的数组。我的目标是找到键(“名称”)并使用其底层数组值在网页中输出。

Array
(
    [E-mail] => Array
        (
            [0] => Your e-mail address is spelled incorrectly
            [1] => Another error just to annoy you further
        )
)

【问题讨论】:

  • 有些事情不清楚我是如何用javascript写的?
  • 那么问题出在哪里? $.each( array, function(key, value) {...
  • 让我问你一个问题:这个数组是从哪里来的?只是好奇。
  • 我很抱歉。我忘了提到我正在使用 jQuery 的 makeArray 函数来转换我在 AJAX 调用后收到的这个字符串。这就是我尝试将其转换为数组的方式... :)

标签: javascript jquery arrays multidimensional-array foreach


【解决方案1】:

Javscript 中没有关联数组,这意味着得到这个:

Array
(
    [E-mail] => Array
        (
            [0] => Your e-mail address is spelled incorrectly
            [1] => Another error just to annoy you further
        )
)

您不会使用数组,而是使用对象,然后该对象将包含消息数组。这是一个例子:

var data = {
   email : [
      "Your e-mail address is spelled incorrectly",
      "Another error just to annoy you further"
   ]
};

现在,要循环环绕您的 data.email 数组,您可以使用 jQuery 的 $.each 或简单地使用 Array.prototype.forEach 本机方法

data.email.forEach(function (item, index) {
    console.log(item);
});

使用$.each

$.each(data.email, function (index, item) {
    console.log(item);
});

【讨论】:

  • 感谢您的评论,我没有意识到 jQuery 中不存在关联数组。我很抱歉。我想我会尝试以 JSON 格式传递数据,这样会更好吗?
  • 是的,这样会更好
猜你喜欢
  • 2014-05-01
  • 2020-09-18
  • 1970-01-01
  • 2013-04-01
相关资源
最近更新 更多