我试图像循环访问数组一样对象。我努力将循环计数器追加到变量名称。通过具有增量属性名称的对象循环访问
我有一个这样的对象(output with dump()
, which I found here):
object(2): {
elem0: array(4): {
[0]: string(27): "http://placehold.it/300x300"
[1]: string(3): "0.8"
[2]: string(4): "-150"
[3]: string(3): "200"
}
elem1: array(4): {
[0]: string(27): "http://placehold.it/300x300"
[1]: string(3): "0.6"
[2]: string(3): "-70"
[3]: string(3): "458"
}
}
下面是我通过它试图循环:
jQuery(document).ready(function($) {
// Provides object-measuring functionality
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Returns the number of objects in my object
var size = Object.size(window.depthElems);
/*
This is where I'm having difficulty.
I would like to use window.depthElems.elem0,
then window.depthElems.elem1, etc.
*/
for (var i = 0; i < size; i++) {
$('.wrapper').append('<img src="' + window.depthElems.elem+i+[0] + '" />');
}
});
你为什么要遍历它像一个数组而不是使用'for(window.depthElems中的元素)''然后''window.depthElems [element]''? – KilZone 2012-07-25 18:12:19
比console.log更好的建议是console.dir http://stackoverflow.com/a/11656075/90648;) – Azder 2012-07-25 18:19:39
@Azder控制台并不总是可用,所以我很满意'dump( )'。 – 2012-07-25 18:25:23