了解Javasciprt中的算法

时间:2019-07-19 13:47:29

标签: javascript arrays hashtable

我开始学习Javascript中的算法,并且发现了一个奇怪的结构,称为哈希表,在幕后是无法理解的。

function findSumBetter(arr, weight) {
    var hashtable = {};

    for (var i = 0; i < arr.length; i++) {
        var currentElement = arr[i],
        difference = weight - currentElement;

        if (hashtable[currentElement] != undefined) {
            return [i, hashtable[currentElement]];
        } else {
            hashtable[difference] = i;
        }
    }

    return -1;
}

console.log(findSumBetter([1,2,3,4,5], 9)); // [4, 3]

1 个答案:

答案 0 :(得分:-1)

好的,这是一个简单的例子:  假设您有JSON对象

Assigning value 
 1 ) hashtable:{'Test1':90,'test2':45,'test3':60};
 // here Test1,Test2,Test3 are keyes
 2 ) hashtable['test1']=90
Getting value:

 1) hashtable['Test1'] 
 2) hashtable.test1  
Both will return the same result 90 in this example.

--------在您的情况下-------

 -- condition to check value is there 
  if (hashtable[currentElement] != undefined)
 -- you are assigning value to object
   hashtable[difference] = i;
 -- returning the value from object
   return [i, hashtable[currentElement]];