JavaScript中的哈希表 [英] Hash table in JavaScript

查看:116
本文介绍了JavaScript中的哈希表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中使用哈希表,我想在哈希表中显示以下值

I am using a hash table in JavaScript, and I want to show the values of the following in a hash table

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

我找到了以下代码。它适用于以下数据。

I have found the following code. It works for the following data.

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

如何将一个[1,2]值分配给哈希表,我如何访问它?

How do I assign one-[1,2] values to a hash table and how do I access it?

<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>

我该怎么做?

推荐答案

使用上面的函数,你会这样做:

Using the function above, you would do:

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

当然,以下内容也适用:

Of course, the following would also work:

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

因为JavaScript中的所有对象都是哈希表!但是,由于使用 foreach(对象中的var项目)也可以获得它的所有功能等等,因此迭代会更难,但这可能足够取决于你的需求。

since all objects in JavaScript are hash tables! It would, however, be harder to iterate over since using foreach(var item in object) would also get you all its functions, etc., but that might be enough depending on your needs.

这篇关于JavaScript中的哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆