Skip to content

Storage

[TOC]

索引

属性

  • storage.lengthnumber,只读,表示存储中键值对的总数。

方法

Storage

属性

length

storage.lengthnumber,只读,表示存储中键值对的总数。

  • 返回:

  • lengthnumber,返回当前存储对象中的键值对数量。

  • js
    // 假设我们已经在 localStorage 中设置了一些键值对
    localStorage.setItem('username', 'JohnDoe');
    localStorage.setItem('age', '30');
    localStorage.setItem('city', 'New York');
    
    // 获取 localStorage 中的键值对数量
    console.log(localStorage.length);  // 输出: 3

方法

getItem()

storage.getItem()(key),返回key对应的value。

  • keystring,存储项的标识符。

  • 返回:

  • valuestring | null,返回与指定key相关联的值。不存在key则返回null。

  • js
    // 存储一个对象
    var userObj = { name: 'John Doe', age: 30 };
    localStorage.setItem('user', JSON.stringify(userObj));
    
    // 获取对象并解析
    var userFromStorage = localStorage.getItem('user');
    var parsedUser = JSON.parse(userFromStorage);
    console.log(parsedUser);  // 输出: { name: 'John Doe', age: 30 }

setItem()

storage.setItem()(key,value),将key和value添加到存储中。如果key存在则更新对应的值。

  • keystring,存储项的标识符。

  • valuestring,希望存储的数据。

  • js
    // 存储一个字符串
    localStorage.setItem('username', 'JohnDoe');
    
    // 存储一个数字(数字会被自动转换为字符串)
    localStorage.setItem('age', 25);
    
    // 存储对象
    var userObj = { name: 'John Doe', age: 30 };
    localStorage.setItem('user', JSON.stringify(userObj));
    
    // 存储数组
    var arr = [1, 2, 3, 4];
    localStorage.setItem('numbers', JSON.stringify(arr));

removeItem()

storage.removeItem()(key),将该key从存储中删除。

  • keystring,要删除的存储项的键。不存在key则不会做任何事。

  • js
    // 假设当前没有 'email' 键的存储项
    localStorage.removeItem('email');  // 不会做任何事情,也不会抛出错误

clear()

storage.clear()(),清空存储中的所有key。

  • js
    // 假设存储了多个键值对
    localStorage.setItem('username', 'JohnDoe');
    localStorage.setItem('age', '30');
    
    // 清空所有存储项
    localStorage.clear();
    
    // 尝试获取任何键的数据,都会返回 null
    console.log(localStorage.getItem('username'));  // 输出: null
    console.log(localStorage.getItem('age'));  // 输出: null

key()

storage.key()(index),根据索引获取存储对象中的指定键。

  • indexnumber,要获取的存储项的索引位置。从0开始。

  • 返回:

  • keystring | null,返回的是存储对象中指定位置的键名。如果超出范围返回null。

  • js
    // 假设存储了多个键值对
    localStorage.setItem('username', 'JohnDoe');
    localStorage.setItem('age', '30');
    localStorage.setItem('city', 'New York');
    
    // 遍历所有存储项的键名
    for (let i = 0; i < localStorage.length; i++) {
        console.log(localStorage.key(i));  // 输出每个存储项的键名
    }