Storage: key() メソッド
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
key()
は Storage
インターフェイスのメソッドで、数値 n を渡すと、指定された Storage
内で n 番目のキーの名称を返します。キーの順序はユーザエージェント依存であり、この順序に頼るべきではありません。
構文
js
key(index)
引数
index
-
名称を取得したいキーの番号を表す整数。これは 0 から始まるインデックスです。
返値
キーの名前を持つ文字列です。該当のインデックスが存在しない場合は null
が返ります。
例
以下の関数は、ローカルストレージのキー全体に対して反復処理を行います。
js
function forEachKey(callback) {
for (let i = 0; i < localStorage.length; i++) {
callback(localStorage.key(i));
}
}
以下の関数は、ローカルストレージのキーを反復処理し、各キーに設定された値を取得します。
js
for (let i = 0; i < localStorage.length; i++) {
console.log(localStorage.getItem(localStorage.key(i)));
}
メモ: 現実世界のの例として、Web Storage Demo をご覧ください。
仕様書
Specification |
---|
HTML # dom-storage-key-dev |
ブラウザーの互換性
Report problems with this compatibility data on GitHubdesktop | mobile | server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
key |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.