javascript数组/对象问题

时间:2012-11-08 16:58:41

标签: javascript jquery arrays

我正在尝试将元素推送到数组上。

修改

 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数组中有8个元素,包含2到3个元素。

这是指函数中的对象。 知道如何解决我的问题吗?

1 个答案:

答案 0 :(得分:1)

您正在为每个循环创建一个新的group对象,因此对group.contents的引用只是当前的一个,它引用之前创建的group对象。

因此,每次调用group.contents.push时,您只是推动在该循环迭代中创建的对象。

相关问题