English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
key() The method returns the name of the key with the specified index.
The key() method belongs to the storage object and can belocalStorageobject orsessionStorrageobject.
The order of the keys is determined by the user-Defined by the agent, so you should not rely on it.
localStorage.key(index)
sessionStorage.key(index)
var x = localStorage.key(0);Test and See‹/›
The numbers in the table specify the first browser version that fully supports the key() method:
Method | |||||
key() | 4 | 3.5 | 11.5 | 4 | 9 |
Parameter | Description |
---|---|
index | An integer representing the index of the key to be retrieved. This is an index starting from zero |
Return value: | A string containing the key name. IfIndexIf not present, it returns null |
---|---|
DOM version: | Network Storage API |
The following function iterates over the local storage keys:
function displayItems() { var items = ""; for(var i = 0; i < localStorage.length; i++) { items += localStorage.key(i) + "<br>"; } document.getElementById("output").innerHTML = items; }Test and See‹/›
The following function traverses the local storage keys and retrieves the values set for each key:
function displayItems() { var items = ""; for(var i = 0; i < localStorage.length; i++) { items += localStorage.key(i) + : "; items += localStorage.getItem(localStorage.key(i)) + "<br>"; } document.getElementById("output").innerHTML = items; }Test and See‹/›
The following function adds two data items to the current domain's session storage and then returns the name of the first session storage item:
var x = sessionStorage.key(0);Test and See‹/›
HTML Tutorial:Web Storage API
Window (Window) Reference:window.localStorage Property
Window (Window) Reference:window.sessionStorage Property