简体   繁体   English

如何从某个字符串开始删除localStorage数据?

[英]How to remove localStorage data starting with a certain string?

I want to remove Firebase-related localStorage. 我想删除与Firebase相关的localStorage。 I tried this: 我试过这个:

  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
  }

However they are not being removed at all. 然而,他们根本没有被删除。

What am I doing wrong? 我究竟做错了什么?

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

This can never be true. 这永远不可能是真的。 You're getting a string 3 characters long and comparing it to "firebase:". 你得到一个长3个字符的字符串,并将其与“firebase:”进行比较。 Just change your 3 to a 9 so it looks like this: 只需将3更改为9即可,如下所示:

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

You don't need to use any extra array and a loop. 您不需要使用任何额外的数组和循环。

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

JS JS

u have to specify the substrig totally 9 charatcers starts with 0 你必须指定subtrig共9个charatcers从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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM