0

Hello I have a piece of code that checks a value against an array and if that value is not found in the array, then it adds that value to another array (called the soldListingArray). It then saves the soldListingArray to the localStorage (using localStorage.setItem("array", soldListingArray). For some reason, in my console I can see that the variable is the correct one, after adding it to the array, but outside of the code when I call for the entire array, it says it's empty.

array1 is the array I'm checking all the values inside against the array2 array.

Here is my code:

    function checkToSeeIfListingIsSold() {

    var soldListingArray = localStorage.getItem("array");

    var x = 0;
    var y = array1.length;

    do {

        var index = array1[x];

        if (array2.indexOf(index) == -1) {

            // Here I add the variable to my soldListingArray

            soldListingArray[soldListingArray.length] = index;

            // Here my console says what has been added to the soldListingArray (the value is correct).

            console.value += index + " has been added to soldListingArray;\n";
            }

         x++;

        } while (x < y)

   localStorage.setItem("array", soldListingArray);

   // Here I ask my console to display my soldListingArray but I get an empty array back.

   console.value += "Sold Array: " + soldListingArray;

   }

Why wasn't the index variable added and saved to my soldListingArray?

Any help is appreciated! Thanks in advance.

The Man
  • 89
  • 1
  • 10

1 Answers1

1

You need to convert the array to a string if you want to use local storage:

localStorage.setItem("array",JSON.stringify(soldListingArray))

Then when you need to access it later and add items, you convert it back to an array:

soldListingArray = JSON.parse(localStorage.getItem("array"));

This has been answered before; a little research would go a long way: Storing Objects in HTML5 localStorage

Community
  • 1
  • 1
Greg Rozmarynowycz
  • 2,037
  • 17
  • 20
  • Would this mess up my array at all? – The Man Jan 28 '15 at 21:10
  • 1
    Nope, you can stringify and parse over and over and over and you'll always get the value back exactly as it was before. – Kevin B Jan 28 '15 at 21:10
  • 1
    It wouldn't unless there's a problem with your code or how your array is formatted – Greg Rozmarynowycz Jan 28 '15 at 21:10
  • Alright thanks this should work for me. I didn't know localStorage could only store strings. I used it once before to save integers but I guess that it did the conversion automatically then. Anyway thanks for clearing that up. I'll try out the code later tonight. – The Man Jan 28 '15 at 21:16