admin管理员组文章数量:1129457
I want to show all of the keys and storage written before. My code is below. I created a function (allStorage) but it doesn't work. How can I do this?
function storeUserScribble(id) {
var scribble = document.getElementById('scribble').innerHTML;
localStorage.setItem('userScribble',scribble);
}
function getUserScribble() {
if ( localStorage.getItem('userScribble')) {
var scribble = localStorage.getItem('userScribble');
}
else {
var scribble = 'You can scribble directly on this sticky... and I will also remember your message the next time you visit my blog!';
}
document.getElementById('scribble').innerHTML = scribble;
}
function clearLocal() {
localStorage.clear();
return false;
}
function allStorage() {
var archive = [];
for (var i = 0; i<localStorage.length; i++) {
archive[i] = localStorage.getItem(localStorage.key(i));
}
}
I want to show all of the keys and storage written before. My code is below. I created a function (allStorage) but it doesn't work. How can I do this?
function storeUserScribble(id) {
var scribble = document.getElementById('scribble').innerHTML;
localStorage.setItem('userScribble',scribble);
}
function getUserScribble() {
if ( localStorage.getItem('userScribble')) {
var scribble = localStorage.getItem('userScribble');
}
else {
var scribble = 'You can scribble directly on this sticky... and I will also remember your message the next time you visit my blog!';
}
document.getElementById('scribble').innerHTML = scribble;
}
function clearLocal() {
localStorage.clear();
return false;
}
function allStorage() {
var archive = [];
for (var i = 0; i<localStorage.length; i++) {
archive[i] = localStorage.getItem(localStorage.key(i));
}
}
Share
Improve this question
edited Jun 8, 2018 at 22:37
matt2000
1,07311 silver badges17 bronze badges
asked Jul 19, 2013 at 11:43
user1942359user1942359
1,6393 gold badges14 silver badges8 bronze badges
3
|
13 Answers
Reset to default 195The easiest way in ES2015+ is:
const items = { ...localStorage };
If you modify your function to this you can list all items based on key (will list the items only):
function allStorage() {
var values = [],
keys = Object.keys(localStorage),
i = keys.length;
while ( i-- ) {
values.push( localStorage.getItem(keys[i]) );
}
return values;
}
Object.keys
is a new addition to JavaScript (ECMAScript 5). It lists all own keys on an object which is faster than using a for-in loop which is the option to this.
However, this will not show the keys. For that you need to return an object instead of an array (which is rather point-less IMO as this will bring you just as far as you were before with localStorage just with a different object - but for example's sake):
function allStorage() {
var archive = {}, // Notice change here
keys = Object.keys(localStorage),
i = keys.length;
while ( i-- ) {
archive[ keys[i] ] = localStorage.getItem( keys[i] );
}
return archive;
}
If you want a compact format listing then do this instead - here each item in the array will have key=item
which you later can split into pairs and so forth:
function allStorage() {
var archive = [],
keys = Object.keys(localStorage),
i = 0, key;
for (; key = keys[i]; i++) {
archive.push( key + '=' + localStorage.getItem(key));
}
return archive;
}
The easiest way would be to use:
return JSON.stringify(localStorage);
localStorage
is not an array, but an object, so try sth. like this:
for (var a in localStorage) {
if (!localStorage.hasOwnProperty(a)) continue;
console.log(a, ' = ', localStorage[a]);
}
// iterate localStorage
for (let i = 0; i < localStorage.length; i++) {
// set iteration key name
const key = localStorage.key(i);
// use key name to retrieve the corresponding value
const value = localStorage.getItem(key);
// console.log the iteration key and value
console.log('Key: ' + key + ', Value: ' + value);
}
for (let [key, value] of Object.entries(localStorage)) {
console.log(`${key}: ${value}`);
}
A little more succinct:
function getAllLocalStorage() {
return Object.keys(localStorage)
.reduce((obj, k) => {
return { ...obj, [k]: localStorage.getItem(k)}}, {});
}
To get all of the "localStorage", copy it and set the localStorage
where you want
let localstorage = {...localStorage};
let content = 'localStorage.clear();';
$.each(localstorage, (i, e) => {
content += `localStorage.setItem('${i}','${e}');`;
})
copy(content);
You can use for loop with hasOwnProperty
to check if object has key.
for (var key in localStorage) {
if (localStorage.hasOwnProperty(key)) {
console.log(key, ' = ', localStorage[key]);
}
}
This will return all of the set keys
const getLocalStorageObject = () => {
storage = {}
let index = 0
while (localStorage.key(index) !== null) {
const key = localStorage.key(index);
storage[key] = localStorage.getItem(key)
index += 1
}
return storage;
}
I hope it helps you, I added a rest parameter, this allows only leaving the properties that are needed
localStorage.setItem("clear", "values")
const {clear, ...rest } = localStorage;
function allStorage(val) {
const { ...rest } = localStorage;
return val ? Object.keys(rest) : Object.values(rest);
}
console.log(allStorage(false));
Get an array of localStorage keys this way:
console.log('keys: ', localStorage._keys)
Should probably be obvious from trying out the 'Correct Answer', but if you want to iterate through or search just the key names, localStorage._keys
is your simple starting point.
These are all bulky or downright incorrect.
The Correct Answer is:
JSON.parse(JSON.stringify(localStorage))
本文标签: javascriptHow to retrieve all localStorage items without knowing the keys in advanceStack Overflow
版权声明:本文标题:javascript - How to retrieve all localStorage items without knowing the keys in advance? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736745396a1950747.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
length
is spelled aslenght
in your code. FYI. – tymeJV Commented Jul 19, 2013 at 14:12Object.keys(localStorage)
– vsync Commented May 10, 2023 at 11:58