使用localStorage开发笔记应用时页面输出出现undefined问题求助
笔记应用输出出现undefined问题解决
我尝试用所学的localStorage开发了一款笔记应用,但在页面输出笔记内容时,会伴随出现undefined字样。
原代码:
let button = document.querySelector('.add'); let text = document.querySelector('.text'); let info = document.querySelector('.info'); let notesarray = []; let notes = localStorage.getItem("notes"); if (notes != null) { notesarray = JSON.parse(notes); } showNotes(); button.addEventListener("click", () => { console.log("we entered"); let text1 = text.value; if (text1.length > 1) { notesarray.push(text.value); localStorage.setItem("notes", JSON.stringify(notesarray)); console.log(notesarray); showNotes(); } }); function showNotes() { let ans; notesarray.forEach((e) => { ans += `<div>${e}</div> <br/>` }) info.innerHTML = ans; }
输出情况:
页面输出时,笔记内容前会先显示"undefined"字样,之后才是正常添加的笔记内容。
问题原因:
showNotes函数中的ans变量未初始化就直接进行字符串拼接。未赋值的变量默认值为undefined,第一次拼接操作会将undefined转为字符串并添加到结果中,最终导致页面输出出现多余的undefined。
解决方法:
将showNotes函数里的let ans;修改为let ans = '';,初始化一个空字符串,后续拼接时就不会引入undefined了。
修改后的完整代码:
let button = document.querySelector('.add'); let text = document.querySelector('.text'); let info = document.querySelector('.info'); let notesarray = []; let notes = localStorage.getItem("notes"); if (notes != null) { notesarray = JSON.parse(notes); } showNotes(); button.addEventListener("click", () => { console.log("we entered"); let text1 = text.value; if (text1.length > 1) { notesarray.push(text.value); localStorage.setItem("notes", JSON.stringify(notesarray)); console.log(notesarray); showNotes(); } }); function showNotes() { let ans = ''; // 初始化空字符串 notesarray.forEach((e) => { ans += `<div>${e}</div> <br/>`; }) info.innerHTML = ans; }
内容的提问来源于stack exchange,提问作者Ankit
相关产品推荐
相关产品推荐

