我有一个简单的待办事项列表应用程序,我想保存/加载添加的项目。每次添加项目时,我都使用以下代码将项目添加到 localStorage:
localStorage.setItem("LIST_ITEM_" + makeid(24), uinput); //makeid() generates random strings
我将密钥设置为 LIST_ITEM_ 和随机 24 个字符的字符串
我使用以下代码从 localStorage 加载项目:
for (i in localStorage) { // Iterate through the cookies
for (const [key,value] of Object.entries(localStorage)) { // Create key-value pairs for each
if (key.includes("LIST_ITEM")) { // Check if the key is a LIST_ITEM
// Create elements to display the item
}
}
}
问题出现在页面上,每个项目似乎加载了 8 次,而不是应该只加载一次。
我运行此代码来查看 localStorage 中的内容:
for (i in localStorage) {console.log(localStorage[i])}
得到了这个:
ww
VM1809:1 w
VM1809:1 2
VM1809:1 ƒ clear() { [native code] }
VM1809:1 ƒ getItem() { [native code] }
VM1809:1 ƒ key() { [native code] }
VM1809:1 ƒ removeItem() { [native code] }
VM1809:1 ƒ setItem() { [native code] }
实际输入的按键是“w”和“ww”。
页面显示:
w
ww
8次。
不确定我做错了什么,但这绝对不应该发生。
当您迭代一个对象时,它还会获得从原型继承的可枚举属性。在
localStorage
的情况下,包括所有方法。使用 hasOwnProperty()
过滤掉继承的属性。
for (i in localStorage) {
if (localStorage.hasOwnProperty(i)) {
console.log(i, localStorage[i]);
}
}