使用for-in循环遍历localStorage出现多余条目问题求助
避免for-in遍历localStorage时出现多余属性的解决方法
问题原因
for-in循环会遍历对象的所有可枚举属性,包括原型链上继承的属性。localStorage属于Storage对象,本身自带length、getItem、key这些内置方法和属性,它们都是可枚举的,所以会被一起遍历出来。
解决方案
1. 使用hasOwnProperty()过滤继承属性
直接在原有循环中增加判断,只处理localStorage自身的属性:
for (const key in localStorage) { if (localStorage.hasOwnProperty(key)) { const notes = document.getElementById("notes"); const value = localStorage.getItem(key); notes.innerHTML += `${key}: ${value} <br>`; } }
2. 使用Object.keys()获取自身键集合
Object.keys()只会返回对象自身的可枚举属性,避免遍历原型链:
const notesElement = document.getElementById("notes"); let content = ''; Object.keys(localStorage).forEach(key => { const value = localStorage.getItem(key); content += `${key}: ${value} <br>`; }); notesElement.innerHTML = content;
这里顺便优化了DOM操作:只获取一次元素,先拼接完整HTML再赋值,比循环内反复修改innerHTML性能更好。
3. 使用Storage原生API遍历(推荐)
Storage对象提供了length属性和key(index)方法,这是官方推荐的遍历方式:
const notesElement = document.getElementById("notes"); let content = ''; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); const value = localStorage.getItem(key); content += `${key}: ${value} <br>`; } notesElement.innerHTML = content;
内容的提问来源于stack exchange,提问作者user20545624
相关产品推荐
相关产品推荐

