字典

字典数据结构是利用arr,基于object来实现的

  1. function Dictionary() {
  2. this.dataStore = []
  3. this.add = add
  4. this.remove = remove
  5. this.find = find
  6. this.clear = clear
  7. this.showAll = showAll
  8. this.count = count
  9. }
  10. function add(k, v) {
  11. this.dataStore[k] = v
  12. }
  13. function remove(k) {
  14. delete this.dataStore[k]
  15. }
  16. function find(k) {
  17. return this.dataStore[k]
  18. }
  19. function clear() {
  20. this.dataStore = []
  21. }
  22. function showAll() {
  23. var keys = Object.keys(this.dataStore)
  24. for (var i = 0; i < keys.length; i++) {
  25. console.log(`key: ${keys[i]} --- value: ${this.dataStore[keys[i]]}`)
  26. }
  27. }
  28. function count () {
  29. return Object.keys(this.dataStore).length
  30. }
  31. var pDic = new Dictionary()
  32. pDic.add('a', 1)
  33. pDic.add('b', 2)
  34. pDic.add('c', 3)
  35. pDic.add('d', 4)
  36. console.log(pDic.find('c'))
  37. console.log(pDic.remove('c'))
  38. pDic.showAll()
  39. console.log(pDic.count())
  40. pDic.clear()
  41. console.log(pDic.count())