字典和散列表是用来储存唯一值(不重复的值)的一种数据结构。在字典中我们使用[key,value]的形式来存储数据。哈希表(散列表)也是一样使用[key,value]来存储数据。但是两种实现方式略哟不同,例如字段中每个健只能有一个值。

字典

  1. function defaultToString(item) {
  2. if (item === null) {
  3. return 'null';
  4. } else if (item === undefined) {
  5. return 'undefined';
  6. } else if (typeof item === 'string' || item instanceof String) {
  7. return `${item}`;
  8. }
  9. return item.toString()
  10. }
  11. class ValuePair {
  12. constructor(key, value) {
  13. this.key = key;
  14. this.value = value;
  15. }
  16. toString() {
  17. return `[#${this.key}]:${this.value}`;
  18. }
  19. }
  20. class Dictionary {
  21. constructor(toStrFn = defaultToString) {
  22. this.toStrFn = toStrFn;
  23. this.table = {};
  24. }
  25. hasKey(key) {
  26. return this.table[this.toStrFn(key)] !== null;
  27. }
  28. set(key, value) {
  29. if (key !== null && value !== null) {
  30. const tableKey = this.toStrFn(key);
  31. this.table[tableKey] = new ValuePair(key, value);
  32. return true
  33. }
  34. return false;
  35. }
  36. remove(key) {
  37. if (this.hasKey(key)) {
  38. delete this.table[this.toStrFn(key)];
  39. return true;
  40. }
  41. return false;
  42. }
  43. get(key) {
  44. if (this.hasKey(key)) {
  45. return this.table[this.toStrFn(key)]
  46. }
  47. return null;
  48. }
  49. keyValues() {
  50. return Object.values(this.table);
  51. }
  52. keys() {
  53. return this.keyValues().map(element => element.key)
  54. }
  55. values() {
  56. return this.keyValues().map(element => element.value)
  57. }
  58. // 迭代字典中的每个键值对
  59. forEach(callbackFn) {
  60. const keyValues = this.keyValues();
  61. debugger
  62. for (let i = 0; i < keyValues.length; i++) {
  63. const result = callbackFn(
  64. keyValues[i].key,
  65. keyValues[i].value
  66. )
  67. // 什么情况下会返回 false ? 有懂得大哥回复下
  68. if (result === false) {
  69. break;
  70. }
  71. }
  72. }
  73. size() {
  74. return Object.keys(this.table).length;
  75. }
  76. isEmpty() {
  77. return this.size === 0;
  78. }
  79. clear() {
  80. this.table = {};
  81. }
  82. toString() {
  83. if (this.isEmpty()) return '';
  84. const valuePairs = this.keyValues();
  85. let objString = `${valuePairs[0].toString()}`;
  86. for (let i = 1; i < valuePairs.length; i++) {
  87. objString = `${objString}, ${valuePairs[i].toString()}`;
  88. }
  89. return objString;
  90. }
  91. }