2012-07-25 104 views
0

我試圖像循環訪問數組一樣對象。我努力將循環計數器追加到變量名稱。通過具有增量屬性名稱的對象循環訪問

我有一個這樣的對象(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] + '" />'); 
    } 

}); 
+2

你爲什麼要遍歷它像一個數組而不是使用'for(window.depthElems中的元素)''然後''window.depthElems [element]''? – KilZone 2012-07-25 18:12:19

+0

比console.log更好的建議是console.dir http://stackoverflow.com/a/11656075/90648;) – Azder 2012-07-25 18:19:39

+0

@Azder控制檯並不總是可用,所以我很滿意'dump( )'。 – 2012-07-25 18:25:23

回答

3

我會,因爲參數的緣故,還提供我的問題作爲答案。您可以使用:

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說,這是一個很好的保障。

+0

我將此標記爲正確答案,因爲它[爲我創建問題](http://stackoverflow.com/questions/11657897/mystery-elements-appearing-when-appending/11657943#11657943)。儘管如此,我仍然從中學到了東西,所以它仍然是積極的。 – 2012-07-25 20:20:05

+0

如果解決方案造成問題,那麼您將其標記爲正確的答案是正確的。然而,在這種情況下,問題不在於解決方案,而在於使用,因爲這兩個答案(我的和現在'正確的'使用完全相同的代碼(for ...){}')。不同之處在'hasOwnProperty(key,obj)'我忘了(抱歉!),我會更新答案。同樣,不使用'Object.size'函數既快速又優雅(您只需循環一次)。 – KilZone 2012-07-25 21:10:42

+0

此外,只是要清楚的問題是談論一個包含數組的**對象**。在這種情況下,使用我的原始代碼是安全的,請不要'取消'我的答案是正確的,因爲您更改了使用案例(我對您的問題的回答是正確的)。 – KilZone 2012-07-25 21:21:05

2

我很抱歉,如果我的答案超過了頂端,我只是想避免由於使用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 = [[],[],[]]

+0

這是很多要學習。謝謝! – 2012-07-25 18:43:29

+0

哦,順便說一句,我不是手動創建這些對象。 [我試過](http://stackoverflow.com/questions/11648829/creating-js-objects-in-php-with-commas-in-between),但我學會了使用'json_encode'。 – 2012-07-25 18:47:08

+1

我能說什麼,JS遠比PHP優雅,你不寫數組(),你只需使用[]:D – Azder 2012-07-25 18:50:55