【问题标题】:Is it possible to perform push and pop operations on a Javascript hashmap?是否可以在 Javascript hashmap 上执行推送和弹出操作?
【发布时间】:2014-01-30 00:07:46
【问题描述】:

我有一个像这样的 Javascript 哈希图:

var hash = new Object();
hash["1000001"] = {value="red"};
hash["1000002"] = {value="green"};
hash["1000003"] = {value="blue"};

我知道hash.pop() 不起作用。但是,有没有办法找出最后添加到哈希中的元素,以便我可以删除它?

也许我应该这样提出我的问题:“有没有办法找出元素添加到哈希中的顺序?(不为添加到的每个元素添加时间戳字段)哈希)

【问题讨论】:

  • Object.keys(hash).pop() 通常有效。如果您存储对象,则键可以重新排序,因此请注意。

标签: javascript hashmap


【解决方案1】:

不。您必须自己跟踪这一点。比如:

function setOrdered(hash, key, val) {
    if (!(key in hash)) {
        hash.order = hash.order || [];
        hash.order.push(key);
    }
    hash[key] = val;
}
function popOrdered(hash) {
    if (!hash.order || hash.order.length === 0) { 
        throw new Error("Empty hash");
    }
    var lastKey = hash.order.pop();
    var result = hash[lastKey];
    delete hash[lastKey];
    return result;
}

用法:

> var hash = {};
> setOrdered(hash, 'a', 10);
> setOrdered(hash, 'b', 20);
> setOrdered(hash, 'c', 30);
> popOrdered(hash);
30    
> hash
{'a': 10, 'b': 20}

【讨论】:

    【解决方案2】:

    我只存储一个跟踪索引的数组,因为它会保持有序,然后给项目一个推送和弹出功能:

    var hash = new Object();
    hash.indexes=[];
    hash.push = function(index, item) {
      hash[index] = item;
      hash.indexes.push(index);
    }
    hash.pop = function() {
     item = hash.indexes.pop();
     ret_item = hash[item];
     delete hash[item];
     return ret_item;
    }
    hash.push("1000001", {value:"red"});
    hash.push("1000002", {value:"green"});
    hash.push("1000003", {value:"blue"});
    hash.pop()
    //{value: "blue"}
    

    【讨论】:

      猜你喜欢
      • 2012-04-26
      • 2016-09-29
      • 2018-06-12
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      相关资源
      最近更新 更多