理解 Javascript 中的算法
Understanding Algorithms in Javasciprt
我在 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]
好的,这是一个简单的例子:
假设您有 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]];
我在 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]
好的,这是一个简单的例子: 假设您有 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]];