我試圖像循環訪問數組一樣對象。我努力將循環計數器追加到變量名稱。通過具有增量屬性名稱的對象循環訪問
我有一個這樣的對象(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