我使用在JavaScript的哈希表,我要显示在哈希表

以下的值
one   -[1,10,5]
two   -[2]
three -[3, 30, 300, etc.]

我发现下面的代码。它适用于以下数据。

   one  -[1]
   two  -[2]
   three-[3]

如何分配单[1,2]的值为哈希表以及如何访问它?

<script type="text/javascript">
    function Hash()
    {
        this.length = 0;
        this.items = new Array();
        for (var i = 0; i < arguments.length; i += 2) {
            if (typeof(arguments[i + 1]) != 'undefined') {
                this.items[arguments[i]] = arguments[i + 1];
                this.length++;
            }
        }

        this.removeItem = function(in_key)
        {
            var tmp_value;
            if (typeof(this.items[in_key]) != 'undefined') {
                this.length--;
                var tmp_value = this.items[in_key];
                delete this.items[in_key];
            }
            return tmp_value;
        }

        this.getItem = function(in_key) {
            return this.items[in_key];
        }

        this.setItem = function(in_key, in_value)
        {
            if (typeof(in_value) != 'undefined') {
                if (typeof(this.items[in_key]) == 'undefined') {
                    this.length++;
                }

                this.items[in_key] = in_value;
            }
            return in_value;
        }

        this.hasItem = function(in_key)
        {
            return typeof(this.items[in_key]) != 'undefined';
        }
    }

    var myHash = new Hash('one',1,'two', 2, 'three',3 );

    for (var i in myHash.items) {
        alert('key is: ' + i + ', value is: ' + myHash.items[i]);
    }
</script>

我该怎么办呢?

有帮助吗?

解决方案

用上面的功能,你会怎么做:

var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);

当然,下文中也将工作:

var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];

由于JavaScript中的所有对象都是哈希表!它将,但是,更难因为使用foreach(var item in object)也会让你的所有功能,等遍历,但是根据您的需要,可能是不够的。

其他提示

如果你想要做的是存储在一个查找表中的一些静态值,你可以使用的对象常量(由 JSON 使用的格式相同)做它紧凑地:

var table = { one: [1,10,5], two: [2], three: [3, 30, 300] }

,然后使用JavaScript的关联数组语法访问它们:

alert(table['one']);    // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10

您可以使用我的JavaScript哈希表的实现, jshashtable 。它允许任何对象被用作密钥,而不仅仅是字符串。

在Javascript解释本机存储在哈希表中的对象。如果你担心从原型链污染,你总是可以做这样的事情:

// Simple ECMA5 hash table
Hash = function(oSource){
  for(sKey in oSource) if(Object.prototype.hasOwnProperty.call(oSource, sKey)) this[sKey] = oSource[sKey];
};
Hash.prototype = Object.create(null);

var oHash = new Hash({foo: 'bar'});
oHash.foo === 'bar'; // true
oHash['foo'] === 'bar'; // true
oHash['meow'] = 'another prop'; // true
oHash.hasOwnProperty === undefined; // true
Object.keys(oHash); // ['foo', 'meow']
oHash instanceof Hash; // true
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top