在 Javascript 中连接两个哈希表
有时,我们需要使用连接函数合并容器并获得新容器。我们将编写一个静态连接方法,它接受 2 个哈希表并创建一个包含所有值的新哈希表。为简单起见,如果其中任意一个哈希表中存在某个键,我们将利用第二个哈希表中的值覆盖第一个哈希表中的值。
示例
static join(table1, table2) {
// Check if both args are HashTables
if(!table1 instanceof HashTable || !table2 instanceof HashTable) {
throw new Error("Illegal Arguments")
}
let combo = new HashTable();
table1.forEach((k, v) => combo.put(k, v));
table2.forEach((k, v) => combo.put(k, v));
return combo;
}你可以使用来测试此示例 −
示例
let ht1 = new HashTable(); ht1.put(10, 94); ht1.put(20, 72); ht1.put(30, 1); let ht2 = new HashTable(); ht2.put(21, 6); ht2.put(15, 21); ht2.put(32, 34); let htCombo = HashTable.join(ht1, ht2) htCombo.display();
示例
这将给出以下输出 −
0:
1:
2:
3:
4: { 15: 21 }
5:
6:
7:
8: { 30: 1 }
9: { 20: 72 }
10: { 10: 94 } --> { 21: 6 } --> { 32: 34 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP