寻梦旅人

文章 评论 浏览 29

寻梦旅人 2022-05-04 13:56:53
/** 
 * 1. 当一个对象拥有length属性,并且splice属性是个函数,对我们来说就可以看作是一个类数组
 * 2. 既然是类数组,对象的键就是数组的下标,对象的值就是数组当前下标的值
 * 3. 此时撇开length属性不管,这个类数组可以看作:[empty, empty, 3, 4]
 * 4. 当length属性起作用时,它将这个类数组的长度截断了,此时可以看作:[empty, empty]
 * 5. 之后这个类数组进行了两次push操作,结果可以看作:[empty, empty, 1, 2]
 * 6. 当然,这个类数组中还包含push和splice函数以及它的length,但并没有数组的其它方法,所以实 
 * 际上它只是一个对象而已
 */
let obj = {
    '2': 3,
    '3': 4,
    length: 2,
    splice: [].splice,
    push: [].push
};

obj.push(1);
obj.push(2);
console.log(obj); // [empty, empty, 1, 2]
console.log(Object.prototype.toString.call(obj)); // [object Object]

第 46 题:输出以下代码执行的结果并解释为什么?

寻梦旅人 2022-05-04 13:50:49

学习的时候,得留下印记,不然今后如何感慨岁月如梭呢,转眼间,已经关注大佬博客3年了

JavaScript 专题之类型判断(上)

寻梦旅人 2022-05-04 12:25:18

localstorage本身没有时间过期的功能,要是自己封装一个简单的localstorage功能的话,可以使用定时器去实现过期时间的功能,值得注意的是执行定时器后,到指定的时间,记得destroy定时器。

export class mockLocalstorage {
  constructor() {
    this.store = new Map(); // 记录存储数据
  }

  getItem(key) {
    const stringKey = String(key);
    if (this.store.has(stringKey)) {
      return String(this.store.get(stringKey));
    } else {
      return null;
    }
  }

  // time单位是小时
  setItem(key, val, time = "undefined") {
    let stime = null;
    if (typeof time !== "number" && time !== "undefined") {
      throw new Error("设置过期时间的基础单位是小时,请不要破坏规则!");
    }

    if (time !== "undefined") {
      time = time * 60 * 60 * 1000; // h ---> ms
      try {
        let _this = this;
        this.store.set(String(key), val);
        // 设置定时器 定时清空垃圾数据
        stime = setTimeout(() => {
          _this.removeItem(key);
          stime = null;
        }, time);
      } catch (e) {
        stime = null;
        throw new Error(e);
      }
    }
  }

  keys() {
    return Object.keys(this.store);
  }

  removeItem(key) {
    this.store.delete(String(key));
  }

  clear() {
    this.store.clear();
  }

  get length() {
    return this.store.size;
  }
}

测试代码(vue代码)

let _this = this;
let time = null;
this.mockLocalstorage.setItem("name", "duya", 0.01);
console.log(this.mockLocalstorage.getItem("name")); // 测试mockLocalstorage duya

// 检测数据又没有清空

第 104 题:模拟 localStorage 时如何实现过期时间功能?

寻梦旅人 2022-05-04 11:56:35

非常赞。

ES6 系列之 let 和 const

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文