JavaScript--字典 Dictionary类

小鱼儿 2022-05-13 18:00 321阅读 0赞

字典 Dictionary类

  1. /*字典 Dictionary类*/
  2. function Dictionary() {
  3. this.add = add;
  4. this.datastore = new Array();
  5. this.find = find;
  6. this.remove = remove;
  7. this.showAll = showAll;
  8. this.count = count;
  9. this.clear = clear;
  10. }
  11. function add(key, value) {
  12. this.datastore[key] = value;
  13. }
  14. function find(key) {
  15. return this.datastore[key];
  16. }
  17. function remove(key) {
  18. delete this.datastore[key];
  19. }
  20. function showAll() {
  21. var str = "";
  22. for(var key in this.datastore) {
  23. str += key + " -> " + this.datastore[key] + "; "
  24. }
  25. console.log(str);
  26. }
  27. function count() {
  28. /*var ss = Object.keys(this.datastore).length;
  29. console.log("ssss "+ss);
  30. return Object.keys(this.datastore).length;*/
  31. /**/
  32. var n = 0;
  33. for(var key in Object.keys(this.datastore)) {
  34. ++n;
  35. }
  36. console.log(n);
  37. return n;
  38. }
  39. function clear() {
  40. for(var key in this.datastore) {
  41. delete this.datastore[key];
  42. }
  43. }
  44. var pbook = new Dictionary();
  45. pbook.add("Mike", "723");
  46. pbook.add("Jennifer", "987");
  47. pbook.add("Jonathan", "666");
  48. pbook.showAll();//Mike -> 723; Jennifer -> 987; Jonathan -> 666;
  49. pbook.count();//3
  50. pbook.remove("Jennifer");
  51. //pbook.clear();
  52. pbook.showAll();//Mike -> 723; Jonathan -> 666;
  53. pbook.count();//2

发表评论

表情:
评论列表 (有 0 条评论,321人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Python 字典(Dictionary)

    字典是另一种可变容器模型,且可存储任意类型对象。 字典的每个键值 key:value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 \{\} 中

    相关 C# Dictionary 字典

     必须包含名空间System.Collection.Generic      Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值)      键