1. /**
    2. * @param {number} capacity
    3. */
    4. var LRUCache = function(capacity) {
    5. this.size = capacity
    6. this.map = new Map()
    7. };
    8. /**
    9. * @param {number} key
    10. * @return {number}
    11. */
    12. LRUCache.prototype.get = function(key) {
    13. let isExist = this.map.has(key)
    14. if (!isExist) return -1
    15. let item = this.map.get(key)
    16. this.map.delete(key)
    17. this.map.set(key, item)
    18. return item
    19. };
    20. /**
    21. * @param {number} key
    22. * @param {number} value
    23. * @return {void}
    24. */
    25. LRUCache.prototype.put = function(key, value) {
    26. let isExit = this.map.has(key, value)
    27. if (isExit) {
    28. this.map.delete(key)
    29. }
    30. this.map.set(key, value)
    31. if (this.map.size > this.size) {
    32. // 这里有个知识点
    33. // map的entries方法,还有keys方法(可以看mdn)),会返回一个迭代器
    34. // 迭代器调用next也是顺序返回,所以返回第一个的值就是最老的,找到并删除即可
    35. this.map.delete(this.map.entries().next().value[0])
    36. }
    37. return null
    38. };

    本次思路是没问题的 ,不过 this.map.entries().next().value[0] 这个不熟悉导致写了很多for循环和中间变量来存储导致耗时