我同意 Kevin 的观点,他的答案是最好的,但是有时候当你在本地存储器中使用不同的键值时,比如你想让你的公共用户看看他们把物品添加到篮子里的次数,你需要给他们看看添加的次数,然后你可以使用以下方法:
var set = localStorage.setItem('key', 'value');
var element = document.getElementById('tagId');
for ( var i = 0, len = localStorage.length; i < len; ++i ) {
element.innerHTML = localStorage.getItem(localStorage.key(i)) + localStorage.key(i).length;
}
既然问题提到了找到键,我想我应该提到,为了显示每个键和值对,你可以这样做(基于 Kevin 的回答) :
for ( var i = 0, len = localStorage.length; i < len; ++i ) {
console.log( localStorage.key( i ) + ": " + localStorage.getItem( localStorage.key( i ) ) );
}
for (let i=0; i< localStorage.length; i++) {
let key = localStorage.key(i);
let value = localStorage[key];
console.log(`localStorage ${key}: ${value}`);
}