【问题标题】:Please help me about LocalStorage请帮助我了解 LocalStorage
【发布时间】:2021-11-24 09:56:59
【问题描述】:

我还有另外 2 个数组 我想在数组 2 之后添加到数组 1 数组 1 将被保存到变量 lobalstorage 中以供下次运行 当前问题:退出站点后,数组 1 重置为原始值

let arr1 = []

setTimeout(function() {

      setInterval(myTimer, 5000);

      function myTimer() {

        debugger


        if (arr1.length == 0) {
          arr1 = [1, 2, 3, 4, 5]
        } else {
          arr1 = localStorage.getObj("StoreArrToken");

        }
        let arr2 = [6, 8, 10]

        // hàm xử lý lưu giá trị mảng vào LocalStore
        Storage.prototype.setObj = function(key, obj) {
          return this.setItem(key, JSON.stringify(obj))
        }
        Storage.prototype.getObj = function(key) {
          return JSON.parse(this.getItem(key))
        }

        var duplicates = arr2.filter(function(val) {
          return arr1.indexOf(val) == -1;
        });

        debugger
        if (duplicates.length == 0) {
          console.log("Duplicate");
        } else {
          arr1 = arr1.concat(duplicates);
          console.log(arr1);
          // Store
          localStorage.setObj("StoreArrToken", arr1);

        }

      }, 1500000000000000);

【问题讨论】:

  • 您好,欢迎您。对于未来,请记住JavaScript and Java are two different languages
  • 这个超时时间是多少:setTimeout(function(){ /* ... */ }, 1500000000000000)?
  • 在开始无条件执行let arr1=[]之前检查本地存储是否有键为“StoreArrToken”的项。

标签: javascript


【解决方案1】:
  1. 将原型设置移出循环

  2. 将初始对象设置在在循环之外

  3. 为什么要等 17,361,111 年再运行它?

     Storage.prototype.setObj = function(key, obj) {
       return this.setItem(key, JSON.stringify(obj))
     }
     Storage.prototype.getObj = function(key) {
       const str = this.getItem(key);
       return !!str ? JSON.parse(str) : null; // str should never be "0" since we store an array
     };
     let arr1 = localStorage.getObj("StoreArrToken") ||  [1, 2, 3, 4, 5];
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    相关资源
    最近更新 更多