zoukankan      html  css  js  c++  java
  • H5--Web Storage

      在过去的web开发中,对于开发交互式的程序,我们经常使用cookie来满足状态存储的需求。但是这种方式有很多缺点,首先就是大小和数量的限制,一般cookie被限制在4k左右,所以严格来说cookie不算本地存储技术,因为每次发送http请求都要带上cookie,如果数据太多会严重影响传输性能,所以cookie有很多的不足,于是html5中为本地存储定义了新的内容webstorge.
      web Storage提供了一种比cookie更加直观的方式存储的名/值对。
      Web Storage包含以下两种机制:
      1. sessionStorage,为每个给定的源维持一个独立的存储区域,该存储区域在页面会话期间可用(只要浏览器处于打开状态)
      2. localStorage,同样的功能,但是在浏览器关闭,然后打开数据仍然存在。
    这两种机制可通过window.sessionStorage及window.localStorage进行访问
     

    1 属性:

    length属性
    length属性是只读属性,返回整数,表示存储在Storage对象中的数据项的数量
    console.log(sessionStorage.length);

    2 方法:

    setItem()
    将键名添加到存储区域内,如果键名已存在,则更新原来的值,如果不存在,则新增数据项:
     
    // storage对象.setItem(key,value)
    window.sessionStorage.setItem('username','Tom');
     sessionStorage.setItem('password','123');
    getItem()
    getItem()方法用于根据指定的键名返回对应的键值:
    console.log(localStorage.getItem('username'));
    console.log(localStorage.getItem('password'));
    removeItem()
    removeItem()方法用于删除指定键名的数据项,如果不存在与给定的键名,则不执行任何操作:
    localStorage.removeItem('password');
    clear()
    clear()方法用于清除存储的所有数据项:
    localStorage.clear();

     key()

    key()用于返回指定索引值的键名,语法结构是:
    console.log(localStorage.key(0));

     注意:storage中存储键的顺序是按照字母排列的

  • 相关阅读:
    Vasya and Endless Credits CodeForces
    Dreamoon and Strings CodeForces
    Online Meeting CodeForces
    数塔取数 基础dp
    1001 数组中和等于K的数对 1090 3个数和为0
    1091 线段的重叠
    51nod 最小周长
    走格子 51nod
    1289 大鱼吃小鱼
    POJ 1979 Red and Black
  • 原文地址:https://www.cnblogs.com/codexlx/p/12562936.html
Copyright © 2011-2022 走看看