异同
cookie
cookie如何产生
1、在浏览器访问服务器时由服务器返回一个Set-Cookie响应头,当浏览器解析这个响应头时设置cookie。
2、通过浏览器js脚本设置 document.cookie = 'name=monsterooo';
localStorage和sessionStorage
localStorage和sessionStorage都继承于Storage,提供了统一的api来访问和设置数据。api列表为:
- clear 清空存储中的所有本地存储数据
- getItem 接受一个参数key,获取对应key的本地存储
- key 接受一个整数索引,返回对应本地存储中索引的键
- removeItem 接受一个参数key,删除对应本地存储的key
- setItem 接受两个参数,key和value,如果不存在则添加,存在则更新。
localStorage.setItem('order', 'a109');
console.log(localStorage.key(0)); // order
console.log(localStorage.getItem('order')) // a109
localStorage.removeItem('order');
localStorage.clear();
// 对象访问方式同样有效
localStorage.order = 'b110';
localStorage.order; // b110