保存オブジェHTML5localStorage
-
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、google Chrome、Firefoxっていると思うので誤解を招く HTML5Web Storage スペックではなく、ブラウザ特有のバグまたは制限があります。
った意味での 構造化クローン 記述されているアルゴリズム http://www.w3.org/TR/html5/infrastructure.html.んかでんというか私の問題は尽きなく、私のオブジェクトのプロパテれていないenumerable(???)
や回避策?
更新:は、W3Cが変更心の構造化クローン仕様に変更した仕様に合わせます。見 https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111.この問題はなくなっ100%有効ですが、答えがあります。
解決
を見る Apple, Mozilla や Mozillaを再 ドキュメンテーション、機能を限られている。取り扱いさせません。文字列のキーと値のペアになっています。
回避できる stringify 御オブジェクトを格納する前に、解析できるので取り:
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));
他のヒント
バリアントの上のマイナーな改良ます:
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()
はのの "JSONに円形構造の変換" TypeError
がスローされます。
循環参照を格納することはサポートされなければならない場合は、JSON.stringify()
の2番目のパラメータが使用される可能性があります:
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この問題に対処する上でいくつかの質問が既にあります
の円形参照してJavaScriptオブジェクト(JSONに変換)それも 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
の使用をお勧めし抽象化図書館のための多くの特徴ここで説明されていなどのより良い対応しています。多くのオプション:
- jStorage または simpleStorage << 自分の好き
- localForage
- alekseykulikov保存
- Lawnchair
- Store.js << 別のオプション
- OMG
より良いだとして機能し、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;
}
};
あなたは透過的にjavascriptのデータ型(アレイ、論理値、日付、フロート、整数を格納するために localDataStorage に使用することができます、StringとObject)。また、自動的に、文字列を圧縮し、キー(名前)だけでなく、(キー)の値によって、クエリでクエリを容易にし、キーを付けることによって、同じドメイン内のセグメント化された共有ストレージを強制するのに役立ちます、軽量のデータの難読化を提供しています。
[免責事項]私はユーティリティの作者だ[/免責事項]
例:
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 店舗のオブジェクトの文字列です。
EJSONの延長ではなくJSONを支援ります。対応してJSON-安全て:
- 日JavaScript
Date
)- バイナリ(JavaScript
Uint8Array
の結果 EJSON.newBinary)- ユーザ定義型(覧 EJSON.addType.例えば、 もんごういか.ObjectID を実施しました。)
すべてのEJSON serializationsも有効なJSON.例えば、オブジェクトには日付およびバイナリのバッファが連載されEJSONとして:
{ "d": {"$date": 1358205756553}, "b": {"$binary": "c3VyZS4="} }
こちらは自localStorageラッパーを使用ejson
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);
}
}
<のhref = "http://www.typescriptlang.org/play/#src=%2F**%0D%0A%20*%20Silly%20wrapper%20to%20be%20able%20to%20type%20the %20storage%20keys%0Dの%の0Aの20%*%2F%0D%0Aexport%20class%20TypedStorage%3CT%3E%20%7B%の0D%の0Aの%の0Dの%の0A%20%20%20%20public%20removeItem(キー%図3Aの%20keyof%20T)%の3Aの%20void%20%7B%0Dの%の0A%20%20%20%20%20%20%20localStorage.removeItem(キー)%3B%0Dの%の0Aの%20%20%20% 20%20%7Dの%の0Dの%の0A%の0Dの%の0A%20%20%20%20public%20getItem%3CK%20extends%20keyof%20T%3E(キー%の3Aの%の20K)%の3A%の20Tの%5BK%の5Dの20% %7C%20null%20%7B%0Dの%の0A%20%20%20%20%20%20%20%20const%20data%3A%20string%、20%7C%20nullの%20%3次元%20%20localStorage.getItem (キー)%3B%0Dの%の0A%20%20%20%20%20%20%20%20return%20JSON.parse(データ)%3B%0Dの%の0A%20%20%20%20%7D%以下の0D %の0Aの%の0Dの%の0A%20%20%20%20public%20setItem%3CK%20extends%20keyof%20T%3E(キー%3A%20K%2C%20value%3A%20T%5BK%5D)%3A%20void% 20%7B%0D%0Aの%20%20%20%20%20%20%20%20const%20data%3A%20string%20%3次元%20JSON.stringify(値)%3B%0Dの%の0Aの%20%20 %20%20%20%20%20%20localStorage.setItem(キー%2C%の20data)%3B%の0Dの%の0A%20%20%20%20%7Dの%の0Dの%の0A%7Dの%の0D%の0Aの%の0D%は0A%2F%2F%20write%20AN 20%インターフェース%20for%20the%20storage%0D%0Ainterface%20MyStore%20%7B%0Dの%の0A%、20%、20%20age%3A%以下の20numberの%2C%0Dの%の0Aの%20%20%20name%3A%20string%2C% 0D%0A%20%20%20address%の3A%20%7Bcity%が3Astring%の7Dの%の0Dの%の0A%7D用の%0D%0A%0D%0Aconst%20storage%3A%20TypedStorage%3CMyStore%3E%20%3D%20new% 20TypedStorage%3CMyStore%3E()%3B%の0D%の0Aの%の0D%0Astorage.setItem(%22wrong%20key%22%2C%20%22%22)%3B%20%2F%2F%20error%20unknown%20key% 0D%の0Astorage.setItem(%は22age%22%2C%、20%22hello%22)%3B%20%2F%2F%20error%2C%20age%20should%20be%20number%0Dの%0Astorage.setItem(%22address%22 %2C%、20%7Bcity%3A%の22Here%22%の7D)%3B%20%2F%2F%20ok%0D%0A%以下の0D%0Aconst%20address%3A%20%7Bcity%3Astring%以下の(d)の%20%3D%以下20storage.getItem(%22address%22)%の3B」REL = "nofollowをnoreferrer">使用例の
// 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(...)
.しかしんで来ることもできるこのことを知っています。I 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オブジェクト *たい店です 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.構文解析.
todosList1 = JSON.parse(localStorage.getItem("todosObject"));
console.log(todosList1);
ローカルストレージをループ
var retrievedData = localStorage.getItem("MyCart");
retrievedData.forEach(function (item) {
console.log(item.itemid);
});