Javascript 显示关联数组中所有元素的键和值
我有一个数组,Javascript 显示关联数组中所有元素的键和值,javascript,jquery,associative-array,Javascript,Jquery,Associative Array,我有一个数组,clientList: [ [ clientID: "123" data: "data1" ] [ clientID: "456" data: "data2" ] [ clientID: "789" data: "data3" ] ] 我试图遍历所有3个数组,显示每个数组的所有键和值 我通过执行标准的$.each(clientList,function(){}遍历各个数组 现在我尝试使用$遍历单个数组。每个(
clientList
:
[
[
clientID: "123"
data: "data1"
]
[
clientID: "456"
data: "data2"
]
[
clientID: "789"
data: "data3"
]
]
我试图遍历所有3个数组,显示每个数组的所有键和值
我通过执行标准的$.each(clientList,function(){}
遍历各个数组
现在我尝试使用$遍历单个数组。每个($(this),函数(key,value){}
,但是键只是数字形式的索引,而不是字符串形式的键名。有什么方法可以做到这一点吗
我找到了一个可能的起点,但是没有办法将
$(this)
初始化为{}
,是吗?数组中存在语法错误,如果是这样,我希望是复制错误
var clientList = [{
clientID: "123",
data: "data1"
}, {
clientID: "456",
data: "data1"
}, {
clientID: "789",
data: "data1"
}]
$.each(clientList, function (idx, obj) {
$.each(this, function(key, val){ //you can use `this` or `obj` to iterate over
console.log(key, val)
})
})
演示:
在
each()
回调中这个引用了一个javascript对象,因此在传递到第二个each()
调用时,不应该尝试使用$(这个)
在它周围创建一个jQuery包装器。普通javascript有什么问题吗?可以使用和遍历对象上的键和值
// 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]);
});
});
你需要这样的东西:
var clientList = [
{
clientID: "123",
data: "data1"
},
{
clientID: "456",
data: "data1"
},
{
clientID: "789",
data: "data1"
}
];
$(document).ready(function(){
var output = $('#output');
$.each(clientList, function(index, obj){
output.append('<div>Item ' + index + '</div>');
$.each(obj, function(key, value){
output.append('<div>' + key + ' = ' + value + '</div>');
});
output.append('<br />');
});
});
var clientList=[
{
clientID:“123”,
数据:“数据1”
},
{
clientID:“456”,
数据:“数据1”
},
{
clientID:“789”,
数据:“数据1”
}
];
$(文档).ready(函数(){
变量输出=$(“#输出”);
$.each(客户端列表,函数(索引,obj){
output.append('Item'+index+'');
$。每个(对象、功能(键、值){
output.append(''+key+'=''+value+'');
});
output.append(“
”);
});
});
如果您只想在调试器中打印它们,请尝试Object.entries(YourAssociationArray)数组中缺少一些逗号…;)?这是chrome调试器的复制/粘贴…您可以使用console.log(JSON.stringify(clientList))
来获取objectAh、this和$(this)的正确字符串表示形式-最后。谢谢。+1使用vanilla js,jQuery很不错,但它不能代替理解jQuery实际上在做什么。IE 11不支持Object.keys