2

我有一个 js,对象是这样的:

function test{
this.variable = {};
this.populate = function(){
  // do some crap....
  // and i populate the object like this
  this.variable{xyz..} = new object();
}
this.outputThecrap(){
for (var key in data) {
    if (data.hasOwnProperty(key)) {
     if(data[key].idParent != '0'){
            //do some stuff
     } 
     }
  }
}
this.addSomeOnBeginigQQ(){
  // how do i do that!!!!Q_Q
  this.variable{blabla...} = new blabla();
}
}

现在在我填充对象之后

var t = new test();
t.populate();
t.addSomeOnBegining();
t.outputThecrap();

我得到的问题是添加的属性在循环结束时结束......我需要它们在顶部

任何人都知道如何解决这个问题?

更新:

对象的结构不可更改。我也不能将数组用作容器,这是不可能的。

4

1 回答 1

0

如果你想要一个堆栈,你将需要使用一个Array- 一个具有定义顺序的列表。JavaScript 中没有对象属性,没有像“关联数组”这样的东西。此外,你应该原型。

您可以像设置对象一样设置数组的属性,但属性名称必须是数字(即整数)。然后你用for-loop 循环它们。Array对象还有一些额外的方法,例如在开头或结尾添加项目(我在下面使用过):

function Test() {
    this.data = []; // an array
}
Test.prototype.populate = function(){
    // populate the array like this
    this.data.push({…});
};
Test.prototype.outputThecrap = function(){
    for (var i=0; i<this.data.length; i++) {
        var item = this.data[i];
        if (item /* has the right properties*/)
             //do some stuff
    } 
};
Test.prototype.addSomeOnBeginning(){
    this.data.unshift({…});
};

然后像这样使用它:

var t = new Test();
t.populate();
t.addSomeOnBeginning();
t.outputThecrap();

“有序键数组”如下所示:

function Test() {
    this.data = {}; // the object
    this.order = []; // an array
}
Test.prototype.populate = function(){
    this.data["something"] = {…}
    this.order.push("something");
};
Test.prototype.addSomeOnBeginning(){
    this.data["other"] = {…};
    this.order.unshift("other");
};
Test.prototype.outputThecrap = function(){
    for (var i=0; i<this.order.length; i++) {
        var key = this.order[i],
            item = this.data[key];
        if (item && key /* fulfill your requirements */)
             // do some stuff
    } 
};
于 2012-08-27T11:07:53.627 回答