javascript jQuery $.each() 没有按预期处理对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7821828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery $.each() not working on object as expected
提问by dSquared
I have the following object:
我有以下对象:
var objectVar = {
4 : { "key" : "key-name4", "item4" : {} },
3 : { "key" : "key-name3", "item3" : {} }
}
I then try the following:
然后我尝试以下操作:
$(objectVar).each(function(index,record){
console.log(record); // Loops Only Once and Logs Full Object
});
Can anyone help me with why the $.each();
function inst iterating through the sub objects within the main object?
任何人都可以帮助我解释为什么$.each();
函数会遍历主对象中的子对象吗?
Any help would be appreciated!
任何帮助,将不胜感激!
回答by user113716
"Can anyone help me with why the $.each(); function inst iterating through the sub objects within the main object?"
“谁能帮我解释一下为什么 $.each(); 函数在主对象中迭代子对象?”
To loop the sub objects, you need sub loops.
要循环子对象,您需要子循环。
While using the each()
[docs]method like you have will usuallysometimes work (as it currently is), it is really meant for DOM elements.
虽然像您这样使用each()
[docs]方法通常有时会起作用(就像目前一样),但它确实适用于 DOM 元素。
Instead use the jQuery.each()
[docs]method:
而是使用jQuery.each()
[docs]方法:
$.each( objectVar, function(index,record){
console.log(record);
// start a loop on the current record in the iteration
$.each( record, function( index2, sub_record ) {
console.log( index2, sub_record );
});
});
Now your looping will be extended to the first level of nested objects.
现在您的循环将扩展到嵌套对象的第一级。
If you're not sure of the overall structure, and want to enumerate the entire depth, you'll need to test each value encountered to see if it should be enumerated.
如果您不确定整体结构,并想枚举整个深度,则需要测试遇到的每个值,看看是否应该枚举它。
回答by Guffa
回答by DrStrangeLove
$.each(objectVar,function(index,record){
console.log(record);
});
回答by Joe
While jQuery is great, you really aren't using it. JavaScript looping through objects is fairly simple as is:
虽然 jQuery 很棒,但您实际上并没有使用它。JavaScript 遍历对象非常简单,如下所示:
var record;
for(var key in objectVar) {
record = objectVar[key];
}
回答by dgilland
You're using $.each()
incorrectly for non-jQuery objects:
您$.each()
对非 jQuery 对象的使用不正确:
$.each( objectVar, function( index, record ){
console.log( record );
});