什么是 javascript 中的哈希?如何对数组使用散列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11070033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:00:31  来源:igfitidea点击:

What is a Hash in javascript? How can i use a hash for an array?

javascripthash

提问by RaviTeja

I'm using an array in my object prototype which basically has add, remove, search functions attached to it.

我在我的对象原型中使用了一个数组,它基本上附加了添加、删除、搜索功能。

Something like this

像这样的东西

myobj = function() {
  this.Array_ = [];
}

myobj.prototype.add = function(item) {
  goog.array.insert(this.Array_, item);
}

myobj.prototype.hasItem = function(item) {
  goog.array.contains(this.Array_, item);
}

And a sample Array in my case would list of integers. [1, 2, 3, 4]

在我的例子中,一个示例数组是整数列表。[1, 2, 3, 4]

But later I learnt that this is very costly and can be cost saving if I use hash. Can someone explain use of hash with the above example.

但后来我了解到这非常昂贵,如果我使用哈希可以节省成本。有人可以用上面的例子解释哈希的使用。

回答by georg

The word "hash" has many meanings, but in this case it probably refers to generic javascript Objects, which are "hashtables" internally. Objects have "add" and "contains" functionality built-in:

“hash”这个词有很多含义,但在这种情况下,它可能指的是通用的javascript对象,它们在内部是“hashtables”。对象具有内置的“添加”和“包含”功能:

foo = {}

foo['x'] = 1   // "add"
'x' in foo     // "contains"

Do note, however, that keys are always converted to strings, therefore if you want keys of other types (e.g. generic objects), you'll have to use custom functions, for example:

但是请注意,键总是转换为字符串,因此如果您想要其他类型的键(例如通用对象),则必须使用自定义函数,例如:

contains = function(ary, obj) {
    return ary.indexOf(obj) >= 0;
}

add = function(ary, obj) {
    if (!contains(ary, obj))
        ary.push(obj)
}