Storage length 属性
实例
获取此域的本地存储项的数量:
<!DOCTYPE html><html><body><p>此示例演示如何使用 length 属性获取本地存储对象中存储的项数量。</p><button onclick="myFunction()">获取存储项数量</button><p id="demo"><script>function myFunction() {var x = localStorage.length;document.getElementById("demo").innerHTML = x;}</script></body></html>
定义与用法
length 属性返回存储在此特定域的浏览器存储对象中的项目数量。
length 属性属于存储对象,它可以是 localStorage 对象或 sessionStorrage 对象。
浏览器支持
| 属性 | |||||
|---|---|---|---|---|---|
| length | 4 | 8 | 3.5 | 4 | 10.5 |
语法
localStorage.length;
或者:
sessionStorage.length;
技术细节
| DOM 版本: | Web Storage API |
|---|---|
| 返回值: | 一个整数,表示存储的项目数 |
更多实例
实例
相同的示例,但使用 sessionStorage 会话存储而不是本地存储。
获取此域的会话存储项目数量:
<!DOCTYPE html><html><body><p>此示例演示如何使用 length 属性获取会话存储对象中存储的项数量。</p><h2>丢失会话存储项项?</h2><p>由于会话存储中可能没有存储任何项目,因此我们添加了一个脚本,为您创建了一些项目。</p><button onclick="createItems()">创建会话存储项目</button><p>单击按钮以获取会话存储项目的数量:</p><button onclick="myFunction()">获取项目数量</button><p id="demo"><script>function createItems() {sessionStorage.test1 = "hello";sessionStorage.test2 = "Jim";sessionStorage.test3 = 358;}function myFunction() {var x = sessionStorage.length;document.getElementById("demo").innerHTML = x;}</script></body></html>
实例
循环浏览每个本地存储项并显示名称:
<!DOCTYPE html><html><body><p>此示例演示如何循环此域的所有本地存储项。</p><h2>丢失会话存储项项?</h2><p>由于会话存储中可能没有存储任何项目,因此我们添加了一个脚本,为您创建了一些项目。</p><button onclick="createItems()">创建会话存储项目</button><h2>显示项目</h2><p>点击按钮显示所有项目:</p><button onclick="displayItems()">显示项目</button><p id="demo"><script>function createItems() {localStorage.setItem("mytime", Date.now());localStorage.setItem("myname", "John");localStorage.setItem("myage", 36);}function displayItems() {var l, i;document.getElementById("demo").innerHTML = "";for (i = 0; i < localStorage.length; i++) {x = localStorage.key(i);document.getElementById("demo").innerHTML += x + "<br>";}}</script></body></html>