【发布时间】:2014-06-17 11:12:16
【问题描述】:
我正在尝试使用 init 方法创建一个对象数组,当我将一个对象推入数组时,它应该将另一个对象推入数组,同时跟踪数组的长度。问题就是在所有对象都添加完之后才更新数组的长度,所以当每个对象试图去抓取长度的时候,都得到0。 我怎样才能让它在这个过程中更新长度? 这是 jfiddle:http://jsfiddle.net/bg3Vg/13/ 如您所见,它给出了一条消息,显示 grouptotal 为 5,但似乎总数从最后一个推送的对象到第一个.. 我需要它以正确的顺序工作,以便最后一个推送的对象可以检索正确的长度。
var colorGroup = [];
var grouptotal = 0;
colorGroup.push(new groupdata(0) );
alert(grouptotal+","+colorGroup[colorGroup.length-1].parent);
function groupdata(parent) {
this.parent = parent;
this.refnum;
this.init = function()
{
grouptotal++;
this.refnum = colorGroup.length;
if(grouptotal<5)colorGroup.push(new groupdata( this.refnum ) );
}
this.init();
}
编辑: 好的,我找到了解决我的问题的方法。让我知道这个解决方案有多可怕..http://jsfiddle.net/EqAqv/1/
var colorGroup = [];
var grouptotal = 0;
var colorGroupWait = [];
colorGroup.push(new groupdata(0) );
while(colorGroupWait.length>0){
var newcolorGroup = colorGroupWait.shift();
colorGroup.push(new groupdata(newcolorGroup) );
}
alert(grouptotal+","+colorGroup[colorGroup.length-1].parent);
alert(grouptotal+","+colorGroup[colorGroup.length-2].parent);
function groupdata(parent) {
this.parent = parent;
this.refnum;
this.init = function()
{
grouptotal++;
this.refnum = colorGroup.length;
if(colorGroup.length<5)colorGroupWait.unshift( this.refnum );
}
this.init();
}
【问题讨论】:
-
你为什么尝试通过他们的
refnum引用groupdata实例而不是简单地通过对象引用? -
我不确定我是否理解您的问题。我试图计算有多少对象被设置为推送,以便它们引用数组中的正确 id。虽然我不能使用 for 循环..
-
不,我想问你需要什么
refnum?例如,将实例传递为parent而不是某个数字会更容易。
标签: javascript arrays push init