0

要素を配列にプッシュしようとしています。

編集

 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);

group.contents各配列に 1 つの要素しかない 8 つの要素が表示されます。group.contents理想的な状況は、配列内に 2 ~ 3 個の要素を持つ 8 個の要素を持つことです。

this は関数内のオブジェクトを参照します。私の問題を解決する方法はありますか?

4

1 に答える 1

1

group ループごとに新しいオブジェクトを作成しているため、参照group.contentsは現在のもののみであり、以前に作成されたオブジェクトは参照されません。group

したがって、 を呼び出すたびgroup.contents.pushに、そのループの繰り返しで作成されたオブジェクトにプッシュするだけです。

于 2012-11-08T17:04:52.973 に答える