Monday, May 27, 2013

Arrays in localStorage

Have you ever tried to create an array with a localStorage variable? When you tried to get one of the values in the array, was all you got a single letter?

If so, the best way to solve this is by constructing the array as a regular localStorage variable.

In this example, I'll use localStorage.array. Let's say that this array uses the value "Rick", "Mark", and "Kathy".

localStorage.array=["Rick","Mark","Kathy"];

I want to get localStorage.array[1], which should return "Mark". But when I access "1", it usually will return the value "i" in this case, which is the second letter in the value. So to solve this problem, we'll use the split() method in JavaScript to return the localStorage value as an array. The character to split could be anything, but I'll use "||". Also note that you shouldn't write it as a standard array; write it like it's a non-array variable.

localStorage.array="Rick||Mark||Kathy";

Now, to access what would be "Mark", we'd simply insert this wherever we want the value used:

localStorage.array.split("||")[1]

So, again, in order to return a localStorage variable as an array, you must first choose a/some character(s) to split the array values. Then write the variable normally and use that/those character(s) that you specified. When you want to access a certain value, use the split() function and the number.

No comments:

Post a Comment

Please keep your comments appropriate.