2014-02-20 23 views
0

我對每個帖子都有一個數據庫註釋。它根據該帖子在一個查詢中提取帖子和所有評論,並將它們分組到XML節點中。我獲得了每個節點中的屬性數量,並拿走了每個帖子默認的標準數量的屬性,並且留下了多少條評論。xml attributes-> javascript multi array->函數/進程數

註釋結構如下:

comment0   Hey nice post! 
commentdate0  2014-12-1 08:25:02 
commentaudthor0 Chris 
comment1   cool! 
commentdate1  2014-08-2 09:25:02 
commentaudthor1 Jason 

等,通過該號碼的評論增加。

所以我需要檢查有多少評論有(完成),然後從XML節點檢索它們(使用$(this).attr('comment'+i))我會在哪裏計數器(comment0, comment1等)

這裏是我當前的代碼把它放入數組:

var comms = new Array(); 
var count = this.attributes.length; 
var av = count-11; 
if(av != 0) { 
    for(var i=0; i<av; i++) { 
     for(var j=0; j<2; j++){ 
      comms[i][j] = $(this).attr('comment'+i); 
      comms[i][j+1] = $(this).attr('commentdate'+i); 
      comms[i][j+2] = $(this).attr('commentauthor'+i); 
     } 
    } 
} 

但它給我以下錯誤:

Uncaught TypeError: Cannot set property '0' of undefined 

現在,我怎樣才能將其加載到多二維數組存儲數據,將其傳遞給一個函數,然後分別處理每一行?

即:這就是我想要做的事:

Array { 
    'comment1': 
     comment 
     commentdate 
     commentauthor 
    'comment2': 
     comment 
     commentdate 
     commentauthor 
} 

,然後我將如何能夠處理函數內各有何評論?即:每個評論,做到這一點。

在此先感謝!

+0

這實在不是一個明智的XML屬性使用! – Eric

+1

爲什麼你想要評論1和評論2?只需製作一個數組並使用此代碼即可。 – lordkain

+0

爲什麼你要循環使用'j'? – Eric

回答

0

您需要在添加之前創建內部數組。試試這個:

var comms = new Array(); 
var count = this.attributes.length; 
var av = count-11; 
//if(av != 0) { // I commented this condition out, as it is not needed here 
    for(var i=0; i<av; i++) { 
     comms[i] = []; // Create a new array here before adding to it (this syntax is more common than the longer "new Array()" syntax you used 
     comms[i][0] = $(this).attr('comment'+i); 
     comms[i][1] = $(this).attr('commentdate'+i); 
     comms[i][2] = $(this).attr('commentauthor'+i); 
    } 
//} 
+0

我試過了,然後我將'comms'數組傳遞給一個函數,但是如何在該函數中'解密'它呢? – user3241507

+0

如果你的電話是'myFunc(comms)',那麼你可以訪問它,例如,一個特定的項目,比如'function myFunc(comms){alert(comms [0] [0]);}'。請注意,您可以在第二種情況下重命名「comms」。否則,我不知道你在問什麼...... –

+0

我試過了,它說:'未捕獲的TypeError:無法讀取未定義的屬性'0' – user3241507