储存的物体在本地存储HTML5
-
18-09-2019 - |
题
我想储存JavaScript对象在HTML5 localStorage
, 但是我的目的是显然正在转换成一串。
我可以存储和检索原始JavaScript类型和数组使用 localStorage
, ,但是对象似乎没有工作。他们应该?
这是我的代号:
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
console.log('typeof testObject: ' + typeof testObject);
console.log('testObject properties:');
for (var prop in testObject) {
console.log(' ' + prop + ': ' + testObject[prop]);
}
// Put the object into storage
localStorage.setItem('testObject', testObject);
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('typeof retrievedObject: ' + typeof retrievedObject);
console.log('Value of retrievedObject: ' + retrievedObject);
控制台输出
typeof testObject: object
testObject properties:
one: 1
two: 2
three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]
它看起来我喜欢的 setItem
方法是将输入到一串之前的储存。
我看到这种行为在Safari,铬和火狐,所以我假设这是我误解的 Html5Web储存 规范,不浏览器的特定错误或限制。
我试过有意义的 结构性克隆 中描述的算法 http://www.w3.org/TR/html5/infrastructure.html.我完全不了解什么说,但也许我的问题已经做的与我的对象是特性不可枚举的(???)
是有一个简单的解决方法?
更新:W3C最终改变他们的思想有关的结构性克隆的规范和决定,以更改的规格相匹配的实现。看看 https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111.因此,这个问题不再是100%有效的,但答案仍然可能会感兴趣。
解决方案
看 苹果, Mozilla 和 Mozilla再次 文件的功能似乎是限于只处理string key/value pairs.
一个解决办法可以 转换成字符串 你目前的储存,以及后来分析它的时候你检索:
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
其他提示
在A小调改善变体:
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
由于的短路评价,getObject()
将立即如果null
里不存水回报key
。它也不会抛出SyntaxError
异常,如果是value
""
(空字符串; JSON.parse()
无法处理)。
您可能会发现它很有用这些方便的方法来扩展存储对象:
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
return JSON.parse(this.getItem(key));
}
这样,你得到你真正想要的,即使功能下的API仅支持字符串。
扩展存储对象是一个真棒溶液。对于我的API,我已经创建了一个用于门面和的localStorage然后检查它是否是一个对象或不同时设置和获取。
var data = {
set: function(key, value) {
if (!key || !value) {return;}
if (typeof value === "object") {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
},
get: function(key) {
var value = localStorage.getItem(key);
if (!value) {return;}
// assume it is an object that has been stringified
if (value[0] === "{") {
value = JSON.parse(value);
}
return value;
}
}
字符串化并不能解决所有问题
看来,这里的答案不包括在Javascript中是可能的所有类型,所以这里是关于如何对付他们正确一些短的例子:
//Objects and Arrays:
var obj = {key: "value"};
localStorage.object = JSON.stringify(obj); //Will ignore private members
obj = JSON.parse(localStorage.object);
//Boolean:
var bool = false;
localStorage.bool = bool;
bool = (localStorage.bool === "true");
//Numbers:
var num = 42;
localStorage.num = num;
num = +localStorage.num; //short for "num = parseFloat(localStorage.num);"
//Dates:
var date = Date.now();
localStorage.date = date;
date = new Date(parseInt(localStorage.date));
//Regular expressions:
var regex = /^No\.[\d]*$/i; //usage example: "No.42".match(regex);
localStorage.regex = regex;
var components = localStorage.regex.match("^/(.*)/([a-z]*)$");
regex = new RegExp(components[1], components[2]);
//Functions (not recommended):
function func(){}
localStorage.func = func;
eval( localStorage.func ); //recreates the function with the name "func"
我不建议,以储存功能,因为eval()
是邪可以导致关于安全,优化和调试问题。
一般而言,eval()
绝不应在JavaScript代码中使用。
私有成员
使用JSON.stringify()
用于收纳物品的问题是,该函数不能连载私有成员。
这个问题可以通过覆盖.toString()
方法(存储网络存储数据时被隐式调用)来解决:
//Object with private and public members:
function MyClass(privateContent, publicContent){
var privateMember = privateContent || "defaultPrivateValue";
this.publicMember = publicContent || "defaultPublicValue";
this.toString = function(){
return '{"private": "' + privateMember + '", "public": "' + this.publicMember + '"}';
};
}
MyClass.fromString = function(serialisedString){
var properties = JSON.parse(serialisedString || "{}");
return new MyClass( properties.private, properties.public );
};
//Storing:
var obj = new MyClass("invisible", "visible");
localStorage.object = obj;
//Loading:
obj = MyClass.fromString(localStorage.object);
循环引用
另一个问题stringify
无法处理是循环引用:
var obj = {};
obj["circular"] = obj;
localStorage.object = JSON.stringify(obj); //Fails
在这个例子中,JSON.stringify()
将抛出TypeError
“转换圆形结构,以JSON”。
如果存储的循环引用应当支持,JSON.stringify()
的第二个参数可以使用:
var obj = {id: 1, sub: {}};
obj.sub["circular"] = obj;
localStorage.object = JSON.stringify( obj, function( key, value) {
if( key == 'circular') {
return "$ref"+value.id+"$";
} else {
return value;
}
});
然而,寻找一种有效的解决方案,高度存储循环引用取决于需要要解决的任务,和恢复这样的数据是不平凡的任一。
有已经在这个问题SO处理一些问题:字符串化(转换为JSON)与循环引用 JavaScript对象
有是一个封装了许多解决方案,以便它甚至还支持旧的浏览器称为 jStorage 一个伟大的图书馆p>
可以设置对象
$.jStorage.set(key, value)
和方便地检索它
value = $.jStorage.get(key)
value = $.jStorage.get(key, "default value")
用于本地存储使用JSON对象:
// SET
var m={name:'Hero',Title:'developer'};
localStorage.setItem('us', JSON.stringify(m));
// GET
var gm =JSON.parse(localStorage.getItem('us'));
console.log(gm.name);
//迭代所有本地存储的键和值的
for (var i = 0, len = localStorage.length; i < len; ++i) {
console.log(localStorage.getItem(localStorage.key(i)));
}
// DELETE
localStorage.removeItem('us');
delete window.localStorage["us"];
在理论上,可以以存储与功能的对象:
function store (a)
{
var c = {f: {}, d: {}};
for (var k in a)
{
if (a.hasOwnProperty(k) && typeof a[k] === 'function')
{
c.f[k] = encodeURIComponent(a[k]);
}
}
c.d = a;
var data = JSON.stringify(c);
window.localStorage.setItem('CODE', data);
}
function restore ()
{
var data = window.localStorage.getItem('CODE');
data = JSON.parse(data);
var b = data.d;
for (var k in data.f)
{
if (data.f.hasOwnProperty(k))
{
b[k] = eval("(" + decodeURIComponent(data.f[k]) + ")");
}
}
return b;
}
<强>然而,功能序列化/反序列化是不可靠的,因为它是依赖于实现的 强>
您也可以覆盖默认的存储setItem(key,value)
和getItem(key)
方法来处理的对象/数组像任何其它数据类型。这样,你可以简单地调用localStorage.setItem(key,value)
和localStorage.getItem(key)
像平时那样。
我没有测试过这种广泛的,但它已经出现没有问题工作的一个小项目,我一直在摆弄。
Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function(key, value)
{
this._setItem(key, JSON.stringify(value));
}
Storage.prototype._getItem = Storage.prototype.getItem;
Storage.prototype.getItem = function(key)
{
try
{
return JSON.parse(this._getItem(key));
}
catch(e)
{
return this._getItem(key);
}
}
我到这个职位上打击已关闭由于这个副本另一篇文章后 - 标题为“如何存储在localStorage的阵列?”。这是很好的,除了两个线程实际上提供了一个完整的答案,如何才能维持在localStorage的数组 - 但我已成功基于包含在这两个线程的信息制作一个解决方案
因此,如果其他人是否希望能推动一个阵列内/流行/转换的项目,他们希望该数组存储的localStorage或sessionStorage的确实,在这里你去:
Storage.prototype.getArray = function(arrayName) {
var thisArray = [];
var fetchArrayObject = this.getItem(arrayName);
if (typeof fetchArrayObject !== 'undefined') {
if (fetchArrayObject !== null) { thisArray = JSON.parse(fetchArrayObject); }
}
return thisArray;
}
Storage.prototype.pushArrayItem = function(arrayName,arrayItem) {
var existingArray = this.getArray(arrayName);
existingArray.push(arrayItem);
this.setItem(arrayName,JSON.stringify(existingArray));
}
Storage.prototype.popArrayItem = function(arrayName) {
var arrayItem = {};
var existingArray = this.getArray(arrayName);
if (existingArray.length > 0) {
arrayItem = existingArray.pop();
this.setItem(arrayName,JSON.stringify(existingArray));
}
return arrayItem;
}
Storage.prototype.shiftArrayItem = function(arrayName) {
var arrayItem = {};
var existingArray = this.getArray(arrayName);
if (existingArray.length > 0) {
arrayItem = existingArray.shift();
this.setItem(arrayName,JSON.stringify(existingArray));
}
return arrayItem;
}
Storage.prototype.unshiftArrayItem = function(arrayName,arrayItem) {
var existingArray = this.getArray(arrayName);
existingArray.unshift(arrayItem);
this.setItem(arrayName,JSON.stringify(existingArray));
}
Storage.prototype.deleteArray = function(arrayName) {
this.removeItem(arrayName);
}
示例用法 - 存储简单的字符串中的localStorage数组:
localStorage.pushArrayItem('myArray','item one');
localStorage.pushArrayItem('myArray','item two');
示例性的使用 - 在sessionStorage的阵列中存储的对象:
var item1 = {}; item1.name = 'fred'; item1.age = 48;
sessionStorage.pushArrayItem('myArray',item1);
var item2 = {}; item2.name = 'dave'; item2.age = 22;
sessionStorage.pushArrayItem('myArray',item2);
常见的方法来操作阵列:
.pushArrayItem(arrayName,arrayItem); -> adds an element onto end of named array
.unshiftArrayItem(arrayName,arrayItem); -> adds an element onto front of named array
.popArrayItem(arrayName); -> removes & returns last array element
.shiftArrayItem(arrayName); -> removes & returns first array element
.getArray(arrayName); -> returns entire array
.deleteArray(arrayName); -> removes entire array from storage
更好的你做的功能setter和getter为的localStorage ,这样你将有更好的控制,不会有重复的JSON解析和所有。 它甚至会处理您的(”“)强>空字符串键/数据的情况下顺利进行。
function setItemInStorage(dataKey, data){
localStorage.setItem(dataKey, JSON.stringify(data));
}
function getItemFromStorage(dataKey){
var data = localStorage.getItem(dataKey);
return data? JSON.parse(data): null ;
}
setItemInStorage('user', { name:'tony stark' });
getItemFromStorage('user'); /* return {name:'tony stark'} */
我修改得票最多的回答有点之一。我如果不需要它具有单一功能,而不是2的风扇。
Storage.prototype.object = function(key, val) {
if ( typeof val === "undefined" ) {
var value = this.getItem(key);
return value ? JSON.parse(value) : null;
} else {
this.setItem(key, JSON.stringify(val));
}
}
localStorage.object("test", {a : 1}); //set value
localStorage.object("test"); //get value
此外,如果未设置值,它不是返回null
的false
。 false
具有一定的意义,null
不
上@Guria的回答改进:
Storage.prototype.setObject = function (key, value) {
this.setItem(key, JSON.stringify(value));
};
Storage.prototype.getObject = function (key) {
var value = this.getItem(key);
try {
return JSON.parse(value);
}
catch(err) {
console.log("JSON parse failed for lookup of ", key, "\n error was: ", err);
return null;
}
};
可以使用 localDataStorage 透明地存储的javascript数据类型(阵列,布尔值,日期,浮点型,整型,字符串和对象)。它还提供轻量级数据混淆,自动压缩串,由(key)的数值便于通过键(名称)的查询以及查询,并且有助于通过前缀键强制执行在同一域内分割共享存储器。
[免责声明]我的实用程序的作者[/声明]
示例:
localDataStorage.set( 'key1', 'Belgian' )
localDataStorage.set( 'key2', 1200.0047 )
localDataStorage.set( 'key3', true )
localDataStorage.set( 'key4', { 'RSK' : [1,'3',5,'7',9] } )
localDataStorage.set( 'key5', null )
localDataStorage.get( 'key1' ) --> 'Belgian'
localDataStorage.get( 'key2' ) --> 1200.0047
localDataStorage.get( 'key3' ) --> true
localDataStorage.get( 'key4' ) --> Object {RSK: Array(5)}
localDataStorage.get( 'key5' ) --> null
可以看到,原始值被推崇。
另一种选择是使用现有的插件。
例如 persisto 是,提供了一个简单的接口,以localStorage的/ sessionStorage的和自动化的开源项目持久性表单字段(输入,单选按钮,复选框和)。
(声明:我的作者。)
您可以使用 埃森 将对象存储为字符串。
EJSON是JSON的扩展,支持更多类型。它支持所有 JSON 安全类型,以及:
- 日期(JavaScript
Date
)- 二进制(JavaScript
Uint8Array
或结果 EJSON.newBinary)- 用户定义的类型(参见 EJSON.addType. 。例如, Mongo.ObjectID 就是这样实现的。)
所有 EJSON 序列化也是有效的 JSON。例如,具有日期和二进制缓冲区的对象将在 EJSON 中序列化为:
{ "d": {"$date": 1358205756553}, "b": {"$binary": "c3VyZS4="} }
这是我使用 ejson 的 localStorage 包装器
https://github.com/UziTech/storage.js
我在包装器中添加了一些类型,包括正则表达式和函数
http://rhaboo.org 是一个localStorage的糖层,使你写这样的事情:
var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
one: ['man', 'went'],
2: 'mow',
went: [ 2, { mow: ['a', 'meadow' ] }, {} ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');
它不使用JSON.stringify /解析,因为这将是不准确的,在大的物体缓慢。相反,每个终端值都有自己的localStorage条目。
您可能已经猜到了,我可能有一些做rhaboo; - )
阿德里安。
我由另一种简约包装只有20行代码以允许使用它喜欢它应:
localStorage.set('myKey',{a:[1,2,5], b: 'ok'});
localStorage.has('myKey'); // --> true
localStorage.get('myKey'); // --> {a:[1,2,5], b: 'ok'}
localStorage.keys(); // --> ['myKey']
localStorage.remove('myKey');
为稿用户愿意设定的,并得到输入的性质:
/**
* Silly wrapper to be able to type the storage keys
*/
export class TypedStorage<T> {
public removeItem(key: keyof T): void {
localStorage.removeItem(key);
}
public getItem<K extends keyof T>(key: K): T[K] | null {
const data: string | null = localStorage.getItem(key);
return JSON.parse(data);
}
public setItem<K extends keyof T>(key: K, value: T[K]): void {
const data: string = JSON.stringify(value);
localStorage.setItem(key, data);
}
}
例的使用:
// write an interface for the storage
interface MyStore {
age: number,
name: string,
address: {city:string}
}
const storage: TypedStorage<MyStore> = new TypedStorage<MyStore>();
storage.setItem("wrong key", ""); // error unknown key
storage.setItem("age", "hello"); // error, age should be number
storage.setItem("address", {city:"Here"}); // ok
const address: {city:string} = storage.getItem("address");
下面的代码的一些版本推广的张贴由@danott
它也将实现的删除强>从localStorage的值 并且示出了如何增加了一个Getter和Setter层以便而不是
localstorage.setItem(preview, true)
可以写
config.preview = true
好这里是去:
var PT=Storage.prototype
if (typeof PT._setItem >='u') PT._setItem = PT.setItem;
PT.setItem = function(key, value)
{
if (typeof value >='u')//..ndefined
this.removeItem(key)
else
this._setItem(key, JSON.stringify(value));
}
if (typeof PT._getItem >='u') PT._getItem = PT.getItem;
PT.getItem = function(key)
{
var ItemData = this._getItem(key)
try
{
return JSON.parse(ItemData);
}
catch(e)
{
return ItemData;
}
}
// Aliases for localStorage.set/getItem
get = localStorage.getItem.bind(localStorage)
set = localStorage.setItem.bind(localStorage)
// Create ConfigWrapperObject
var config = {}
// Helper to create getter & setter
function configCreate(PropToAdd){
Object.defineProperty( config, PropToAdd, {
get: function () { return ( get(PropToAdd) ) },
set: function (val) { set(PropToAdd, val ) }
})
}
//------------------------------
// Usage Part
// Create properties
configCreate('preview')
configCreate('notification')
//...
// Config Data transfer
//set
config.preview = true
//get
config.preview
// delete
config.preview = undefined
,那么您可以与剥离.bind(...)
别名部分。不过,我只是把它,因为它真的很好了解这一点。我tooked我小时找出为什么一个简单的get = localStorage.getItem;
不工作
我做的,不打破现有的存储对象的事情,而是创建了一个包装,所以你可以做你想做的。其结果是正常对象,没有方法,与像任何对象访问。
如果你想1个localStorage
属性魔法:
var prop = ObjectStorage(localStorage, 'prop');
如果您需要几个:
var storage = ObjectStorage(localStorage, ['prop', 'more', 'props']);
你做prop
一切,或对象的在 storage
将自动保存到localStorage
。你总是有一个真正的对象播放,所以你可以做这样的东西:
storage.data.list.push('more data');
storage.another.list.splice(1, 2, {another: 'object'});
和每一个新的对象的内强>跟踪对象将被自动跟踪。
<强>的非常大的缺点:强>这取决于Object.observe()
因此它具有非常有限的浏览器支持。它看起来并不像它会很快到来的Firefox或边缘。
让我们假设你有下面的数组称为电影:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
使用字符串化功能,你的电影阵列可以通过使用下面的语法变成一个字符串:
localStorage.setItem("quentinTarantino", JSON.stringify(movies));
请注意,我的数据正在被存储在名为quentinTarantino键之下。
检索数据
var retrievedData = localStorage.getItem("quentinTarantino");
要从字符串转换回对象,使用JSON解析功能:
var movies2 = JSON.parse(retrievedData);
您可以调用所有的阵列方法对你movies2
要存储一个对象,你可以做一个字母,你可以用它来获得从字符串对象的对象(可能是没有意义)。例如
var obj = {a: "lol", b: "A", c: "hello world"};
function saveObj (key){
var j = "";
for(var i in obj){
j += (i+"|"+obj[i]+"~");
}
localStorage.setItem(key, j);
} // Saving Method
function getObj (key){
var j = {};
var k = localStorage.getItem(key).split("~");
for(var l in k){
var m = k[l].split("|");
j[m[0]] = m[1];
}
return j;
}
saveObj("obj"); // undefined
getObj("obj"); // {a: "lol", b: "A", c: "hello world"}
此技术会造成一些小问题,如果你使用,你用于分割对象的信,而且也非常的实验。
使用localStorage的用于从触头保持接收到的消息的轨道文库的一个小例子:
// This class is supposed to be used to keep a track of received message per contacts.
// You have only four methods:
// 1 - Tells you if you can use this library or not...
function isLocalStorageSupported(){
if(typeof(Storage) !== "undefined" && window['localStorage'] != null ) {
return true;
} else {
return false;
}
}
// 2 - Give the list of contacts, a contact is created when you store the first message
function getContacts(){
var result = new Array();
for ( var i = 0, len = localStorage.length; i < len; ++i ) {
result.push(localStorage.key(i));
}
return result;
}
// 3 - store a message for a contact
function storeMessage(contact, message){
var allMessages;
var currentMessages = localStorage.getItem(contact);
if(currentMessages == null){
var newList = new Array();
newList.push(message);
currentMessages = JSON.stringify(newList);
}
else
{
var currentList =JSON.parse(currentMessages);
currentList.push(message);
currentMessages = JSON.stringify(currentList);
}
localStorage.setItem(contact, currentMessages);
}
// 4 - read the messages of a contact
function readMessages(contact){
var result = new Array();
var currentMessages = localStorage.getItem(contact);
if(currentMessages != null){
result =JSON.parse(currentMessages);
}
return result;
}
的localStorage只能存储键值对,其中两个键和值的的必须是字符串即可。但是,可以通过串行化他们JSON
串,然后将它们反序列化到JS对象时检索这些存储的对象。
<强>例如强>
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// JSON.stringify turns a JS object into a JSON string, thus we can store it
localStorage.setItem('testObject', JSON.stringify(testObject));
// After we recieve a JSON string we can parse it into a JS object using JSON.parse
var jsObject = JSON.parse(localStorage.getItem('testObject'));
注意的事实,这将删除已建立的原型链。这是通过一个例子中最佳示出:
function testObject () {
this.one = 1;
this.two = 2;
this.three = 3;
}
testObject.prototype.hi = 'hi';
var testObject1 = new testObject();
// logs the string hi, derived from prototype
console.log(testObject1.hi);
// the prototype of testObject1 is testObject.prototype
console.log(Object.getPrototypeOf(testObject1));
// stringify and parse the js object, will result in a normal JS object
var parsedObject = JSON.parse(JSON.stringify(testObject1));
// the newly created object now has Object.prototype as its prototype
console.log(Object.getPrototypeOf(parsedObject) === Object.prototype);
// no longer is testObject the prototype
console.log(Object.getPrototypeOf(parsedObject) === testObject.prototype);
// thus we cannot longer access the hi property since this was on the prototype
console.log(parsedObject.hi); // undefined
<强>我这个JS对象强> * I要存储在此的 HTML5本地存储强>
todosList = [
{ id: 0, text: "My todo", finished: false },
{ id: 1, text: "My first todo", finished: false },
{ id: 2, text: "My second todo", finished: false },
{ id: 3, text: "My third todo", finished: false },
{ id: 4, text: "My 4 todo", finished: false },
{ id: 5, text: "My 5 todo", finished: false },
{ id: 6, text: "My 6 todo", finished: false },
{ id: 7, text: "My 7 todo", finished: false },
{ id: 8, text: "My 8 todo", finished: false },
{ id: 9, text: "My 9 todo", finished: false }
];
我可以商品强>将此在的 HTML5本地存储强>以这种方式,通过使用的 JSON.stringify 强>
localStorage.setItem("todosObject", JSON.stringify(todosList));
现在我可以得到从本地存储该对象的 JSON.parsing
todosList1 = JSON.parse(localStorage.getItem("todosObject"));
console.log(todosList1);
通过本地存储环
var retrievedData = localStorage.getItem("MyCart");
retrievedData.forEach(function (item) {
console.log(item.itemid);
});