1

I have this situation where I have localStorage keys

0,1,2,3

and if I delete key 1, in my loops it breaks when it gets to position 1, instead of searching for next 2,3 etc. So my idea is when I delete one key, for example key 1, I want all next keys to move up by one place.

I am working with Angular 1.3.

for (var i = 0; i < localStorage.length; i++) {
    $scope.stored_data.push(ls.get(i));
 }

I am also open for alternative solutions to this problem. As long as I get array with data and loops don't break as they iterate through arrays and localStorage it will do.

Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
Kunok
  • 8,089
  • 8
  • 48
  • 89
  • Sounds like a `foreach` problem, not a `for` problem. Try http://stackoverflow.com/a/10768302 – Robert Harvey Feb 07 '16 at 02:08
  • @RobertHarvey but there is a problem. If I for example do this `for (var i in localStorage){ console.log(i); }` the log output is this: `2 1 0 key getItem setItem removeItem clear length` but I only need keys (0,1,2..) and I want to push their values into array. – Kunok Feb 07 '16 at 02:35
  • What if you only took the `i`'s that passed [this test](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger)? – Robert Harvey Feb 07 '16 at 02:40

1 Answers1

0

Here's an alternative way to solve your problem. Instead of storing each value separately, try this:

//Store a list of the values as an array
var list = ["Value 1", "Value 2", "Value 3"];


//Delete the first value of the array, shifting everything forward
list.shift();

//Since local storage only supports strings, we must stringify the array
localStorage["list"] = JSON.stringify(list);

//When it's time to retrieve the list, parse it back to an array from JSON
list = JSON.parse(localStorage["list"]);
Reubend
  • 644
  • 1
  • 6
  • 19