localStorage에 어레이를 어떻게 저장합니까? [복제]
이 질문에 이미 답변이 있습니다.
localStorage가 필요하지 않은 경우 코드는 다음과 같습니다.
var names=new Array();
names[0]=prompt("New member name?");
작동합니다. 그러나이 변수를 localStorage에 저장해야하는데 상당히 고집 스럽습니다. 난 노력 했어:
var localStorage[names] = new Array();
localStorage.names[0] = prompt("New member name?");
내가 어디로 잘못 가고 있습니까?
localStorage
문자열 만 지원합니다. 사용 JSON.stringify()
하고 JSON.parse()
.
var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));
//...
var storedNames = JSON.parse(localStorage.getItem("names"));
localStorage
및 sessionStorage
단지 문자열을 처리 할 수 있습니다. 기본 저장소 개체를 확장하여 배열 및 개체를 처리 할 수 있습니다. 이 스크립트를 포함하고 새로운 방법을 사용하십시오.
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
}
사용 localStorage.setObj(key, value)
배열이나 객체를 저장하고 localStorage.getObj(key)
이를 검색 할 수 있습니다. 동일한 메서드가 sessionStorage
개체 에 대해 작동 합니다.
새 메서드를 사용하여 저장소에 액세스하는 경우 모든 값은 저장하기 전에 JSON 문자열로 변환되고 getter에서 반환되기 전에 구문 분석됩니다.
출처 : http://www.acetous.de/p/152
사용 JSON.stringify()
및 JSON.parse()
더 제안하지 않기 때문에! 이렇게하면 구분 기호 (예 : 멤버 이름 three|||bars
) 를 포함하는 멤버 이름의 드물지만 가능한 문제를 방지 할 수 있습니다 .
방금 만든 :
https://gist.github.com/3854049
//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");
//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');
JSON 접근 방식은 작동합니다. 예를 들어 7에서는 json2.js가 필요하며 완벽하게 작동하며 그렇지 않으면 localStorage가 있다고 언급 한 하나의 주석에도 불구하고 작동합니다. 번거롭지 않은 최상의 솔루션 인 것 같습니다. 물론 기본적으로 json2와 동일한 작업을 수행하는 스크립트를 작성할 수 있지만 그 점은 거의 없습니다.
at least with the following version string there is localStorage, but as said you need to include json2.js because that isn't included by the browser itself: 4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; BRI/2; NP06; .NET4.0C; .NET4.0E; Zune 4.7) (I would have made this a comment on the reply, but can't).
Another solution would be to write a wrapper that store the array like this:
localStorage.setItem('names_length', names.length);
localStorage.setItem('names_0', names[0]);
localStorage.setItem('names_1', names[1]);
localStorage.setItem('names_' + n, names[n]);
Removes the overhead of converting to JSON, but would be annoying if you need to remove elements, as you would have to re-index the array :)
참고URL : https://stackoverflow.com/questions/3357553/how-do-i-store-an-array-in-localstorage
'developer tip' 카테고리의 다른 글
Argparse 선택적 위치 인수? (0) | 2020.10.03 |
---|---|
git 커밋이 어떤 브랜치에서 왔는지 찾기 (0) | 2020.10.03 |
PHP에서 문자열을 숫자로 어떻게 변환합니까? (0) | 2020.10.03 |
jquery를 사용하여 확인란을 선택 / 선택 취소 하시겠습니까? (0) | 2020.10.03 |
Java assert 키워드의 기능은 무엇이며 언제 사용해야합니까? (0) | 2020.10.03 |