简体   繁体   中英

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

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]

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.

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:

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 (eg 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM