我想删除与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
}
然而,它们根本没有被删除。
我做错了什么?
答案 0 :(得分:2)
substring(0,3) == 'firebase:'
这永远不会成真。你得到一个长3个字符的字符串,并将其与“firebase:”进行比较。只需将3更改为9即可,如下所示:
substring(0, 9) == 'firebase:'
答案 1 :(得分:1)
您不需要使用任何额外的数组和循环。
for (key in localStorage) {
if (key.substring(0,9) == 'firebase:') {
localStorage.removeItem(key);
}
}
答案 2 :(得分:0)
<强> JS 强>
你必须指定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)