![](/img/trans.png)
[英]Looping through an object and adding values to a Javascript object with the incremental count as the key
[英]Looping through an object with incremental property names
我試圖像遍歷數組那樣遍歷對象。 我正在努力將循環計數器附加到變量名稱。
我有一個像這樣的對象( 在這里找到dump()
輸出 ):
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(element in window.depthElems) {
if(window.depthElems.hasOwnProperty(element)) {
$('.wrapper').append('<img src="' + window.depthElems[element] + '" />');
}
}
這不僅更優雅,而且需要更少的代碼。 當然,如果有理由使用其他代碼,請這樣說。
注意:對該代碼進行了編輯,使其還具有讀取“數組”的功能,但是問題是要使其與“對象”一起使用。 如果使用“對象”,則“ hasOwnProperty”檢查是多余的。
注意#2:您也可以使用var hasOwn = Object.prototype.hasOwnProperty;
就像Azder所說的那樣,這是一個很好的保障。
如果答案是最重要的話,我深表歉意,我只是想防止因濫用JS(我已經經歷了很多)而進一步受到傷害。
jQuery(document).ready(function($) {
var i; // there is no block scope in JS, so better to be clear and define i here
var $wrapper; // also
// Changing the JS built-in objects is problematic most of the time
// You should learn from jQuery and do wrapping instead
// Or at least just a good namespasing like:
// MyFramework.objectSize = function (obj) {}
Object.size = function(obj) {
var size = 0, key;
var hasOwn = Object.prototype.hasOwnProperty; // will explain further down
for (key in obj) {
// if obj has redifined hasOwnProperty = function(){ return false; }?
// it's better to use hasOwn like this if(hasOwn.call(obj,key)) {}
// and please do use braces even if only 1 statement
if(hasOwn.call(obj,key)) size++;
}
return size;
};
// Returns the number of objects in my JSON object
var size = Object.size(window.depthElems);
$wrapper = $('.wrapper'); // cached so jQuery doesn't search for it each iteration
// i is scoped to the whole function anyways
for (i = 0; i < size; i++) {
// $.each even guards you of the changing DOM which can cause
// infinite loops (you don't have that problem here, but... good to know
$.each(window['depthElems'+i],function(index,element){
$wrapper.append('<img src="' + element + '" />');
});
}
});
另外,由於您已經制作了名為elem1,elem2,elem3等的對象,因此您最好使用二維數組,例如window.depthElems = [[],[],[]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.