【问题标题】:How to remove localStorage data starting with a certain string?如何删除以某个字符串开头的 localStorage 数据?
【发布时间】:2016-07-04 11:35:53
【问题描述】:

我想删除与 Firebase 相关的 localStorage。我试过这个:

  let arr = [] // Array to hold the keys
  // Iterate over localStorage and insert the keys that meet the condition into arr
  for (let i = 0; i < localStorage.length; i++) { // eslint-disable-line
    console.log(localStorage.key(i)) // eslint-disable-line
    if (localStorage.key(i).substring(0,3) == 'firebase:') { // eslint-disable-line
      arr.push(localStorage.key(i)) // eslint-disable-line
    }
  }
  // Iterate over arr and remove the items by key
  for (let i = 0; i < arr.length; i++) {
    localStorage.removeItem(arr[i]) // eslint-disable-line
  }

但是它们根本没有被删除。

我做错了什么?

【问题讨论】:

    标签: javascript firebase local-storage


    【解决方案1】:
    substring(0,3) == 'firebase:'
    

    这永远不会是真的。你得到一个长度为 3 个字符的字符串,并将其与“firebase:”进行比较。只需将您的 3 更改为 9,它看起来像这样:

    substring(0, 9) == 'firebase:'
    

    【讨论】:

      【解决方案2】:

      您不需要使用任何额外的数组和循环。

      for (key in localStorage) {
        if (key.substring(0,9) == 'firebase:') {
          localStorage.removeItem(key);
        }
      }
      

      【讨论】:

        【解决方案3】:

        JS

        你必须指定子串,总共 9 个字符以 0 开头

         localStorage.setItem("abc" , "heelo");
               localStorage.setItem("abc2" , "firebase:")
                for (obj in localStorage) {
              if (localStorage[obj].substring(0,9) == 'firebase:') {
                localStorage.removeItem(obj);
              }
            }
            console.log(localStorage)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-09-08
          • 1970-01-01
          • 2017-09-27
          • 1970-01-01
          • 2019-11-15
          • 2010-09-05
          • 2014-12-02
          • 1970-01-01
          相关资源
          最近更新 更多