有序遍历地图

时间:2015-04-07 16:03:47

标签: javascript sorting dictionary

我的数据结构是Map Objects。 这使得我可以使用键来访问我的对象,这是我需要的。 但是我希望能够使用特定的订单遍历我的结构。

示例:

function Container()
{
    this.data   = new Map();
    this.at     = function(objID)   {   return this.data.get(objID);    }
    this.insert = function(obj)     {   this.data.set(obj.id, obj);     }
    this.remove = function(obj)     {   this.data.delete(obj.id);       }
    this.size   = function()        {   return this.data.size;          }
    this.values = function()        {   return this.data.values();      }
}
var cnt = new Map();
cnt.set({id: 1, order:3});
cnt.set({id: 2, order:1});
cnt.set({id: 3, order:2});

我想添加一个sortedValues方法,让我按顺序访​​问所有对象。

我试过

this.data.values().sort(function(a,b){ return a.order > b.order; });

但排序方法可在Array上使用,而不是在Iterators上。 如何构建有序迭代器?否则我怎么能将.values()迭代器转换为Array

1 个答案:

答案 0 :(得分:0)

由于您的ID是整数,因此您根本不需要地图。从用作哈希表的普通对象中,您可以获得具有Object.keys(数据)或Object.ownPropertyNames(data)的实际键组。以下是使用其他一些很酷的对象功能的示例:

var cnt = Object.create({}, {
  length: { value: 0, enumerable: false, configurable: false },
  set: {
      value: function(obj)
      {
        if(!(obj.id in this)) this.length++
        this[obj.id]=obj
      },
      writable: false, enumerable: false, configurable: false
  },
  remove: {
      value: function(obj)
      {
        if(obj.id in this){
          this.length--
          delete this[obj.id]
        }
      },
      writable: false, enumerable: false, configurable: false
  },
  sorted: {
      value: function()
      {
        return Object.keys(this).sort(function(a,b){return this[a].order - this[b].order}.bind(this))
          .map(function(id){return this[id]}.bind(this))
      },
      writable: false, enumerable: false, configurable: false
  }
})

cnt.set({id: 1, order:3})
cnt.set({id: 2, order:1})
cnt.set({id: 3, order:2})

console.log(cnt.sorted())
相关问题