HTML and CSS Reference
In-Depth Information
Figure 12-2 Removing data using the removeItem() function.
The localStorage object also has a function you can use to retrieve the name of a key from the datastore. This
function is called key() , and it takes an integer that represents the position of a key in the key index. The order in
which keys are stored in this index varies between browsers. This means that you cannot really rely on this function
for finding a specific key, but it does come in handy when trying to retrieve all of the data in LocalStorage; as you
will see in the next example.
Try storing a few key/value pairs and then retrieving all the keys in LocalStorage. Enter each line in the code listing
below into your console. You need to type the entire for loop into the console on one line.
// Store some data.
localStorage.setItem(“name", “Joe Balochio");
localStorage.setItem(“phone", “012-345-6789");
localStorage.setItem(“email", “");
// Retrieve the keys for your data.
for (var i = 0; i < localStorage.length; i++) {
console.log(localStorage.key(i)) };
The for loop in this example will iterate through each piece of data stored in LocalStorage and print the keys to the
console, as Figure 12-3 shows.
Figure 12-3 Finding key names using the key() function.
Search WWH ::

Custom Search