It is necessary that all two keys be erased when the cycle is running.

localStorage.setItem('2', 'lalala'); localStorage.setItem('3', 'lalala'); for (var i = 0; i < localStorage.length; i++) { if (localStorage.key(i) > 1) { alert(localStorage.key(i)); // показывается два ключа localStorage.removeItem(localStorage.key(i)); // удаляется не два, а один } } 
  • somewhere the closing bracket is missing } ? - Grundy
  • I fixed it, thanks - Nik

3 answers 3

You can clear it like this:

 localStorage.clear() 
  • so all keys will be removed in general, and judging by the condition in the code, he wants only those that are more than 1 - Grundy
  • @Grundy, hmm .. I read the title of the question ... - Qwertiy
  • Yeah, but judging by the question itself, it doesn’t seem quite like that. - Grundy
  • @Grundy, I guess. But then he was already answered, and when searching, it may be useful. - Qwertiy

The code works correctly. You have added the keys "2" and "3" and the length is localStorage = 2, so there are only 2 fields. Therefore, the cycle will go to 2, not 3, and will not reach key 3.

  • Not understood. I have only two keys, yes. The length is equal to the number of keys. The loop bypasses all elements> 1 (use alert and it shows). But when you delete, for some reason it does not delete everything. - Nik
  • I think Grundy is right, thanks - Nik

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.

  • localStorage is an object, not an array. His indexes do not move. - Arnial
  • one
    @Arnial, only it was about the keys. localStorage.key (i) here selects the key by the index, after deleting the item, the keys are shifted. - Grundy
  • @Arnial, if we treat localStorage as an object, it generally has no indices. Well, strictly speaking, this is an array-like object, and not just an object, so the behavior can easily be redefined as you like - Grundy