2

I have refereed this question and worked for me: so q1

Now Issue is that I have used JSON.stringify & JSON.parse to store array in localStorage. But when I run the code again and try to use JSON.parse on localStorage nothing get retrived. I dont know whats going wrong.

here is code:

    function BankProDisplay() {
        var myString = JSON.parse(localStorage['bankpro']);
        var mySplitResult = myString.split(",");
        for (i = 0; i < mySplitResult.length; i++) {
            document.getElementById('bankpro').innerHTML = document.getElementById('bankpro').innerHTML + mySplitResult[i] + "<br/>";
        }
    }
Community
  • 1
  • 1
V.J.
  • 918
  • 3
  • 18
  • 37
  • I would do a few tests in the Javascript console while running this code in a browser to check what value is stored at localStorage['bankpro'] to ensure that it is the stringified JSON you are expecting. If you are getting that value out correctly see what happens when you try to JSON.parse(...) that result. – ShelbyZ Oct 17 '12 at 12:35
  • You don't need to serialize your data to store it in localStorage - you can actually just shove an array into localStorage quite happily. – PhonicUK Oct 17 '12 at 12:37

2 Answers2

1

If you store an Array in LocalStorage using JSON.stringify, then you get it back using JSON.parse, return value is Array, not string. So when you are using function mySplitResult for myString (which is actually Array, thanks to JSON.parse), then it leads to an Error. So remove function mySplitResult and it should work fine.

Matti Mehtonen
  • 1,685
  • 14
  • 19
1
var myString = JSON.parse(localStorage['bankpro']);

JSON.parse returns a javascript object, not a string, which would not have a split method.

jbabey
  • 45,965
  • 12
  • 71
  • 94
  • Yup got it. In my code i just converted object to string. And worked fine. myString.toString().split(","); – V.J. Oct 17 '12 at 12:45
  • you don't need the `toString()` - localStorage accessors will always give you a string. glad it helped :) – jbabey Oct 17 '12 at 12:47