2012-11-08 111 views
0

我試圖將元素推送到數組上。javascript數組/對象問題

EDIT

task.prototype.goTest=function(){ 

    for(a = 0; a < test.length; a++) { 
     if(this.testnumber != test[a].number) { 

      //it will only loop 8 times under conditional statement    
      group = { 
       title: test[a].Title, 
       ID: test[a].ID, 
       contents: [] 
      }; 

      this.company.push(group); 
      this.testnumber = test.number[a]; 
     } 
     //outside of if conditional statement.. it will loop 15 times 
     //i want every test[a].conetents get pushed to group.contents array. 
     //this.company is the final variable I need for this function...  

     group.contents.push(test[a].contents); 
    } 
    console.log(this.company); 
} 

然而,當我做

console.log(this.company); 

我看到8個elmements只有1中的每個group.contents數組元素。理想情況是在group.contents陣列中有8個元素,其中包含2到3個元素。

這是指函數中的對象。 任何想法如何解決我的問題?

+3

當你做'console.log'在哪裏?什麼是'這個'?如果我們能夠提供幫助,我們需要更多信息。一些樣本數據也會很好。 – Madbreaks

+0

我認爲你的思想有一個非常困難的算法來解決問題。讓我們談論需求,而不是你的代碼的原因,據我所知,做一件簡單的事情太複雜了。 – Rikki

+0

我剛剛編輯我的帖子。 – FlyingCat

回答

1

你正在一個新的group對象的每個循環中,因此參考group.contents只有當前一個,它參考以前創建的group對象。

所以,每次你打電話group.contents.push,你只是推動在該循環迭代中創建的對象。