是否可以在Javascript hashmap上执行推送和弹出操作?

时间:2014-01-30 00:07:46

标签: javascript hashmap

我有一个像这样的Javascript hashmap:

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

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

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

2 个答案:

答案 0 :(得分: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}

答案 1 :(得分:1)

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

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"}
相关问题