请考虑以下代码和输出。我不知道为什么它最后只处理带有偶数的键。关于它为什么不在最后用奇数处理键的任何想法?我在IE 11中看到了这一点。
try {
localStorage.clear();
for (var i = 0; i < 10; i++) {
var item = 'ir360-grid-' + i;
localStorage.setItem(item, 'test');
}
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
console.log('processing key ' + key);
if (key.startsWith("ir360-grid")) {
console.log("removing: " + key);
localStorage.removeItem(key);
}
}
} catch (e) {
console.log(e);
}
processing key ir360-grid-0
removing: ir360-grid-0
processing key ir360-grid-2
removing: ir360-grid-2
processing key ir360-grid-4
removing: ir360-grid-4
processing key ir360-grid-6
removing: ir360-grid-6
processing key ir360-grid-8
removing: ir360-grid-8
答案 0 :(得分:1)
也会在Chrome上发生。
我很确定会发生这种情况,因为localStorage
是Object
而不是Array
。
在每次迭代中,您都会减少localStorage的长度,因此您只循环了预期的一半,并且由于localStorage是一个Object,因此键不会根据索引而改变。
所以它是这样的:
i = 0
remove localStorage.key(0) // now ir360-grid-1 is at localStorage.key(0) and ir360-grid-2 is at localStorage.key(1)
i = 1
remove localStorage.key(1) // which contains ir360-grid-2, now ir360-grid-3 is at key(1) and ir360-grid-4 is at key(2)
i = 2
remove localStorage.key(2) // which contains ir360-grid-4
and so on...
使用Object
迭代循环解决了这个问题:
for (var i in localStorage) {
var key = localStorage.key(i);
console.log('processing key ' + key);
if (key.startsWith("ir360-grid")) {
console.log("removing: " + key);
localStorage.removeItem(key);
}
}