SessionStorage.key JavaScript Example

SessionStorage.key(): Passed a number to retrieve nth key of a SessionStorage.

Syntax

Syntax for Key() Method:
var KeyName = sessionStorage.key(index);

sessionStorage.key() Method Example

The key() method comes in handy in situations where you need to loop through keys and allows you to pass a number or index to local storage to retrieve the name of the key.
var KeyName = sessionStorage.key(index);
The following function iterates over the local storage keys:
function forEachKey(callback) {
  for (var i = 0; i < sessionStorage.length; i++) {
    callback(sessionStorage.key(i));
  }
}
The following function iterates over the local storage keys and gets the value set for each key:
for(var i =0; i < sessionStorage.length; i++){
  console.log(sessionStorage.getItem(sessionStorage.key(i)));
}

Reference


Comments