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我看到 8 个元素,每个数组中只有 1 个元素。理想的情况是group.contents数组中有 8 个元素和 2 到 3 个元素。

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

4

1 回答 1

1

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

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

于 2012-11-08T17:04:52.973 回答