Looping through localStorage in HTML5 and JavaScript
So, I was thinking I could just loop through localStorage like a normal object as it has a length. How can I loop through this?
localStorage.setItem(1,'Lorem');
localStorage.setItem(2,'Ipsum');
localStorage.setItem(3,'Dolor');
If I do a localStorage.length
it returns 3
which is correct. So I'd assume a for...in
loop would work.
I was thinking something like:
for (x in localStorage){
console.log(localStorage[x]);
}
But no avail. Any ideas?
The other idea I had was something like
localStorage.setItem(1,'Lorem|Ipsum|Dolor')
var split_list = localStorage.getItem(1).split('|');
In which the for...in
does work.
You can use the key
method. localStorage.key(index)
returns the index
th key (the order is implementation-defined but constant until you add or remove keys).
for (var i = 0; i < localStorage.length; i++){
$('body').append(localStorage.getItem(localStorage.key(i)));
}
If the order matters, you could store a JSON-serialized array:
localStorage.setItem("words", JSON.stringify(["Lorem", "Ipsum", "Dolor"]));
The draft spec claims that any object that supports structured clone can be a value. But this doesn't seem to be supported yet.
EDIT: To load the array, add to it, then store:
var words = JSON.parse(localStorage.getItem("words"));
words.push("hello");
localStorage.setItem("words", JSON.stringify(words));
In addition to all the other answers, you can use $.each function from the jQuery library:
$.each(localStorage, function(key, value){
// key magic
// value magic
});
Eventually, get the object with:
JSON.parse(localStorage.getItem(localStorage.key(key)));
The simplest way is:
Object.keys(localStorage).forEach(function(key){
console.log(localStorage.getItem(key));
});
This works for me in Chrome:
for(var key in localStorage) {
$('body').append(localStorage.getItem(key));
}
Building on the previous answer here is a function that will loop through the local storage by key without knowing the key values.
function showItemsByKey() {
var typeofKey = null;
for (var key in localStorage) {
typeofKey = (typeof localStorage[key]);
console.log(key, typeofKey);
}
}
If you examine the console output you will see the items added by your code all have a typeof string. Whereas the built-in items are either functions { [native code] } or in the case of the length property a number. You could use the typeofKey variable to filter just on the strings so only your items are displayed.
Note this works even if you store a number or boolean as the value as they are both stored as strings.
All of these answers ignore the differences between the implementations of localStorage across browsers. Contributors in this domain should heavily qualify their responses with the platforms they are describing. One browser-wide implementation is documented at https://developer.mozilla.org/en/docs/Web/API/Window/localStorage and, whilst very powerful, only contains a few core methods. Looping through the contents requires an understanding of the implementation specific to individual browsers.
localStorage
is an Object
.
We can loop through it with JavaScript for/in Statement just like any other Object.
And we will use .getItem()
to access the value of each key (x).
for (x in localStorage){
console.log(localStorage.getItem(x));
}
참고URL : https://stackoverflow.com/questions/3138564/looping-through-localstorage-in-html5-and-javascript
'Nice programing' 카테고리의 다른 글
HttpStatusCode가 성공 또는 실패를 나타내는 지 확인 (0) | 2020.10.11 |
---|---|
Android SDK로 멀티 파트 요청 게시 (0) | 2020.10.11 |
JS : 날짜가 1 시간 이내인지 확인하세요? (0) | 2020.10.11 |
그룹화 할 때 테이블에서 가장 긴 '문자열'을 선택하는 방법 (0) | 2020.10.11 |
후행 반환 유형 구문 스타일이 새로운 C ++ 11 프로그램의 기본값이되어야합니까? (0) | 2020.10.11 |