문제

고 싶을 저장하려면 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,Chrome,Firefox,그래서 가정 내의 오해가 HTML5 웹 스토리지 사양,지 않는 브라우저 버그의 특정 제한 사항입니다.

내가 하려고 했는 의미의 구조적 복제 알고리즘에서 설명 http://www.w3.org/TR/html5/infrastructure.html.지 않아요 완전히 이해 무엇을 말하고 있지만,아마 내의 문제는 나체의 속성을 아는 열거(???)

이 있는 쉽게 해결 방법?


업데이트:W3C 결국 그들의 마음을 변경에 대해 구조적 복제는 사양,결정을 변경하는 스펙에 맞게 구현합니다..보 https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111.그래서 이 질문은 더 이상 유효한 100%,그러나 답변도 관심이 될 수 있습니다.

도움이 되었습니까?

해결책

애플, MozillaMozilla 시 문서 기능이 제한 될 것으로 보인만 처리할 문자열을 키/값 쌍으로 이루어져 있습니다.

해결 방법이 될 수 있을 변환 귀하의 개체를 저장하기 전에,그리고 나중에 분석을 때 당신이 그것을 검색:

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);
}

short-circuit 평가, getObject()즉시 return 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,내가 만들어 외관에 대한 로컬 저장 확인하고 다음의 경우에는 개체는지를 설정하는 동안 얻.

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;
  }
}

변환하지 않는 모든 문제를 해결

그것은 보인다는 응답을 여기를 커버하지 않는 모든 유형에 가능한 자바 스크립트,그래서 여기에 몇 가지 간단한 예제에 처리하는 방법들을 제대로:

//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() 에 대한 개체를 저장하고 있는 이 기능을 할 수 없습 serialise 개인 회원입니다.이 문제를 해결할 수 있습으로 덮어쓰기 .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;
    }
});

그러나 찾기 위한 효율적인 솔루션을 저장하는 순환을 참조 고도에 의존해야 하는 작업을 해결하고,복원하는 그러한 데이터는 사소한하지 않습니다.

이미 몇 가지 질문에 그래서 이 문제를 다루는: 변환(로 변환하 JSON)자바스크립트 개체 순환을 참조

수있는 좋은 라이브러리는 랩은 솔루션으로도 지원이라는 오래된 브라우저 jStorage

당신은 설정할 수 있는 개체

$.jStorage.set(key, value)

고 그것을 검색 쉽

value = $.jStorage.get(key)
value = $.jStorage.get(key, "default value")

사용체 위해 로컬 저장소:

//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)));
}

//삭제

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) 방법 개체를 처리/배열은 다음과 같은 다른 어떤 데이터 유형이 있습니다.는 방법은,당신은 단순히 call 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);
  }
}

에 도착했을 때 이 게시물을 타격 후에 또 다른 포스트는 폐쇄되었으로 중복 이라는 제목의'저장하는 방법을 배열에는 로컬 저장소?'.는 벌금을 제외하고도 실제적으로 대답을 어떻게 당신을 유지할 수 있는 배열에는 로컬 저장-그러나 제가 관리하는 기술 기반 솔루션에 포함된 정보는 모두에서 스레드입니다.

그래서 다른 사람이 되고 싶어/pop/shift 항목 배열 내에서,그리고 그들은 원하는 배열에 저장된 로컬 또는 실제로 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.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

추천을 사용하여 추상화 라이브러리에 대한 기능의 많은 여기서 설명 뿐만 아니라 더 나은 호환성.많은 옵션:

더 나은 당신이 만드는 기능으로 세터 및 게터 로컬 저장소, 이 방법은 당신이해야 더 나은 제어되지 않습을 반복해야 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

또한,이 값을 설정하지 않으면,그것은 돌아 nullfalse. false 일부 의미 null 하지 않습니다.

개선에@구리아'의 대답:

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 을 투명하게 자바 스크립트 데이터 저장 형태(배열,Boolean,날짜,Float,정수,문자열과 Object).그것은 또한 제공합니다 경량 데이터 난독,자동으로 압축 문자열을 용이하게하여 쿼리를 키(이름)뿐만 아니라 쿼리(key)가치하고,도움을 적용하 세그먼트에서 공유 스토리지 동일한 도메인을 붙여 키를 사용합니다.

[DISCLAIMER]나는 저자의 유틸리티[/면책조항]

예제:

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 오픈 소스 프로젝트이 제공하는 쉬운 인터페이스는 로컬/sessionStorage 및 자동화하는 지속성에 대한 형태로드(입력 라디오 버튼 체크 박스).

persisto features

(면책 조항:나는 저자이다.)

당신이 사용할 수 있는 ejson 를 저장하는 개체를 문자열입니다.

EJSON 의 확장 JSON 더 지원하는 형식입니다.그것을 모두 지원합 JSON-안전한 종류뿐만 아니라:

모든 EJSON 전이 들에도 유효 JSON.예를 들어 있는 객체의 날짜 및 이진 버퍼 것에 연재 EJSON 로:

{
  "d": {"$date": 1358205756553},
  "b": {"$binary": "c3VyZS4="}
}

여기에는 나의 로컬 저장소 래퍼를 사용하여 ejson

https://github.com/UziTech/storage.js

추가 몇 가지 종류 내 래퍼를 포함한 정규 표현식과 기능

http://rhaboo.org 은 로컬 저장소 설탕 층를 작성할 수 있게 해 주는 것 같다:

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.변환/분석기 때문에 하는 것은 부정확하고 느린에서 큰 개체입니다.대신에,각 터미널 값은 그것의 자신의 로컬 저장소 항목입니다.

데 내가 뭔가를 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');

https://github.com/zevero/simpleWebstorage

을 위한 타이프 라이터용하고자 설정을 얻을 입력 속성:

/**
 * 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

그것은 또한 구현 삭제 값에서 로컬 저장소 하는 방법을 보여줍니다 추가 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 me 시간 이유를 찾기 위해 간단한 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() 그래서 그것은 매우 제한된 브라우저 지원합니다.그것처럼 보이지 않는 것이 나오는 대한 파이어 폭스 또는 에지습니다.

말하자 다음과 같은 편이라는 영화:

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"}

이 기술은 결함을 일으킬 경우를 사용하여 문자를 사용하는 분체,그리고 그것은 또한 매우 실험적인 기능이다.

작은 예의 라이브러리를 사용하는 로컬 저장소에 대한 추적을 유지의 메시지를 받은 연락처:

// 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;
 }

로컬 저장소 저장할 수 있는 키-값 쌍으로는 모두의 키와 값 야하는 문자열.그러나,당신이 저장할 수 있는 객체에 의해 직렬화하들 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.변환

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);
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top