--- title: Storage.length slug: Web/API/Storage/length translation_of: Web/API/Storage/length ---

{{APIRef("Web Storage API")}}

length 是 {{domxref("Storage")}} 接口的只读属性,返回一个整数,表示存储在 Storage 对象里的数据项(data items)数量。

语法

var aLength = storage.length;

返回值

一个整数。

示例

下面的函数添加三个数据项到当前域名的本地存储里面,然后返回本地存储里面数据项的数量:

function populateStorage() {
  localStorage.setItem('bgcolor', 'yellow');
  localStorage.setItem('font', 'Helvetica');
  localStorage.setItem('image', 'cats.png');

  localStorage.length; // 返回 3
}

备注: 关于实际的例子,可以查看 Web Storage Demo.

规范

Specification Status Comment
{{SpecName('Web Storage', '#dom-storage-length', 'length')}} {{Spec2('Web Storage')}}  

浏览器兼容性

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
localStorage 4 3.5 8 10.50 4
sessionStorage 5 2 8 10.50 4
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support 2.1 {{ CompatUnknown }} 8 11 iOS 3.2

各浏览器支持的 localStorage 和 sessionStorage 容量不同。测试页面:detailed rundown of all the storage capacities for various browsers.

Note: since iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short.

相关链接

使用 Web Storage API