foreach对象循环添加到堆栈顶部

foreach object looping adding on top of the stack

本文关键字:堆栈 顶部 添加 对象 循环 foreach      更新时间:2023-09-26

我有一个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();

我遇到的问题是,添加的属性最终会出现在循环的末尾。。。我需要他们在的顶端

有人知道如何解决这个问题吗?

更新:

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

如果您想要一个堆栈,则需要使用Array-一个具有定义顺序的列表。JavaScript中没有对象属性,也没有类似于"关联数组"的东西。此外,你应该是原型。

您可以像设置对象一样设置数组的属性,但属性名称必须是数字(即整数)。然后使用for-循环对它们进行循环。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
    } 
};