A problem is akin to a problem with splice .
After deleting an element, all the others have moved, and one element is skipped, as the counter has increased all the same.
To avoid this, you can bypass the collection from the end.
localStorage.setItem('2', 'lalala'); localStorage.setItem('3', 'lalala'); for (var i = localStorage.length - 1; i >= 0; i--) { if (localStorage.key(i) > 1) { console.log(localStorage.key(i)) //показывается два ключа localStorage.removeItem(localStorage.key(i)) //удаляется не два, а один } }
Or, first select all the necessary keys, and only then go through them and delete
localStorage.setItem('2', 'lalala'); localStorage.setItem('3', 'lalala'); Object.keys(localStorage).filter(key=>key>1).forEach(key=>localStorage.removeItem(key))
Also note that the keys and values in localStorage are always only strings. Therefore, if variables of some other type are expected, it is better to lead to it explicitly, in order to avoid unexpected behavior.
}? - Grundy