向关联数组中的所有元素显示键和值

Jef*_*amb 2 javascript jquery associative-array

我有一个数组,clientList:

[
  [
    clientID: "123"
    data: "data1"
  ]
  [
    clientID: "456"
    data: "data2"
  ]
  [
    clientID: "789"
    data: "data3"
  ]
]
Run Code Online (Sandbox Code Playgroud)

我正在尝试迭代所有3个数组,显示每个数组的所有键和值.

我通过标准迭代各个数组$.each(clientList, function() {}.

现在我正在尝试迭代单个数组,$.each($(this), function(key, value) {}但键只是数字形式的索引,而不是字符串的键名.有没有办法做到这一点?

我发现迭代与jQuery.每一个关联数组作为可能的起点,但没有办法初始化$(this){},是吗?

Qan*_*avy 11

纯JavaScript有什么问题?您可以使用Object.keysArray.prototype.forEach浏览对象上的键和值.

// Loops through every single client in the client list.
clientList.forEach(function (client) {
    // Logs each of the key-value pairs on the client object.
    Object.keys(client).forEach(function (key) {
      console.log(key + ': ' + client[key]);
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 使用vanilla js的+1,jQuery很不错,但它不能替代理解jQuery实际上在做什么. (4认同)