【问题标题】:Determine if value exists in JavaScript "hash table"确定 JavaScript“哈希表”中是否存在值
【发布时间】:2019-04-07 04:44:46
【问题描述】:

我已经构建了一个用作哈希表的 JavaScript 对象。

var hashTable = {}; 

该表由手动构建的键值对组成。该表将用于根据表中的旧值或键生成新值。

//hashTable['old_value'] = new_value;
hashTable['115004568543'] = 115004567503;
hashTable['115004545983'] = 360000857366;
hashTable['115004723526'] = 360000865566;
hashTable['115004723646'] = 360000865566;

我有另一个变量与哈希表中的键进行比较。如果它匹配哈希表中的一个键,那么它可以用来捕获映射到它的新值。

例如,假设声明了 some_value。

some_value = '115004568543';

由于它匹配哈希表中的一个键值(或旧值),我可以通过调用来获取新值

var new_value = hashTable[some_value];
// new_value is going to be equal to 115004567503 due to the mapping above

我的问题是我有两个不同的哈希表,“some_value”正在与之进行比较。我想查看哈希中的第一个值是否存在于第一个哈希表或第二个哈希表中。所以我一直在合作:

var hashTable = {};
hashTable['115004568543'] = 115004567503;
hashTable['115004545983'] = 360000857366;

var hashTable2 = {};
hashTable2['115004702483'] = 360000857366;
hashTable2['115004560766'] = 360000857366;

var some_value = '115004545983';

if (hashTable.includes(some_value)) {
    var new_value = hashTable[some_value];
    //Do some other stuff with new_value
}

else if (hashTableTwo.includes(some_value)) {
    var new_value = hashTableTwo[some_value];
    //Do some other stuff with new_value
}

另外,some_value 将存在于第一个哈希表、第二个哈希表中,或者根本不存在。它不会多次存在。

我的问题:我正在尝试使用 hashTable.includes() 来查看两个哈希表中是否存在 some_value。它不工作。确定 some_value 是否是其中一个哈希表中的值的最佳方法是什么?

当我尝试调用 hashTable.includes(some_value) 时,我得到了

Uncaught TypeError: hashTable.includes is not a function

【问题讨论】:

  • hashTable 到底是什么?我猜它是一个普通的对象,而不是一个数组? (你还需要在if 之后使用括号,否则你会得到一个SyntaxError
  • 什么是redirect - 如何“调用”hashTable.includes 产生redirect.includes 不存在的错误?
  • 你的问题不清楚;确保阐明什么是 hashTable,也许可以展示你的实现示例
  • 如果你的hashTable是一个普通对象,你可以使用some_value in hashTable
  • 请说明“值”何时表示哈希表键的值,何时表示键下的值。

标签: javascript arrays object hash


【解决方案1】:

Array.includes() 是一个数组方法。由于您的哈希表是基于对象的,因此不支持此方法。

如果您的值不是虚假的(false、undefined、null、0、NaN),您可以使用逻辑 short-circuit evaluation 来分配值:

var new_value = hashTable[some_value] || hashTableTwo[some_value] || some_value;

如果它们可能是虚假的,您可以使用in operator 来检查它们是否存在于对象中:

if (some_value in hashTable) {
    var new_value = hashTable[some_value];
} else if (some_value in hashTableTwo) {
    var new_value = hashTableTwo[some_value];
    //Do some other stuff
}

【讨论】:

  • 这行得通!非常感谢 Ori Drori。我当然也学到了更多关于 JS 的知识,所以我真的很感激。
猜你喜欢
  • 1970-01-01
  • 2012-02-19
  • 2012-08-10
  • 2011-05-19
  • 2013-02-18
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多