日期:2014-05-16  浏览次数:20445 次

javascript 实现java中的Map (高效)[转]

javascript实现java中的Map,代码是在国外的一个网站上看到的(http://stackoverflow.com/questions/368280/javascript-hashmap-equivalent ),自己稍作了修改,之前也看到过有人用2个数组实现了Map,但是我感觉效率比较低,现在这个我感觉效率还可以,自己做了下测试,代码如下:
Map.js

Java代码 复制代码
  1. function?Map(linkItems)?{? ??
  2. ???? this .current?=?undefined;? ??
  3. ???? this ._size?=? 0 ;? ??
  4. ???? if (linkItems?===? false ){ ??
  5. ???????? this .disableLinking();? ??
  6. ????}? ??
  7. } ??
  8. /** ?
  9. ?*?获取当前map ?
  10. ?*?@return?当前对象 ?
  11. ?*/ ??
  12. Map.noop?=?function()?{? ??
  13. ???? return ? this ;? ??
  14. };? ??
  15. /** ?
  16. ?*?非法操作 ?
  17. ?*?@return ?
  18. ?*/ ??
  19. Map.illegal?=?function()?{? ??
  20. ???? throw ? new ?Error( "非法操作,Map已经被禁用" );? ??
  21. };? ??
  22. /** ?
  23. ?*? ?
  24. ?*?@param?obj ?
  25. ?*?@param?foreignKeys ?
  26. ?*?@return ?
  27. ?*/ ??
  28. Map.from?=?function(obj,?foreignKeys)?{? ??
  29. ????var?map?=? new ?Map;? ??
  30. ???? for (var?prop?in?obj)?{? ??
  31. ???????? if (foreignKeys?||?obj.hasOwnProperty(prop)){ ??
  32. ????????????map.put(prop,?obj[prop]);? ??
  33. ????????}? ??
  34. ????}? ??
  35. ???? return ?map;? ??
  36. };? ??
  37. /** ?
  38. ?*?禁用map ?
  39. ?*?@return ?
  40. ?*/ ??
  41. Map.prototype.disableLinking?=?function()?{? ??
  42. ???? this .link?=?Map.noop;? ??
  43. ???? this .unlink?=?Map.noop;? ??
  44. ???? this .disableLinking?=?Map.noop;? ??
  45. ???? this .next?=?Map.illegal;? ??
  46. ???? this .key?=?Map.illegal;? ??
  47. ???? this .value?=?Map.ille