【发布时间】:2020-06-18 06:45:46
【问题描述】:
我试图在我的代码中访问数组中的对象属性,以呈现从本地存储刷新后恢复的输入框的文本值,但由于某种原因,当我尝试在我的 appStart() 中运行 for 循环时它给我的功能:“未捕获的类型错误:无法在 appStart 读取未定义的属性 'id'”。任何关于为什么会发生这种情况以及如何解决它的见解将不胜感激。
const currentDayPlaceholder = $("#currentDay");
const timeInTimeBlocks = $(".input-group-text");
const timeBlockInput = $(".form-control");
const saveButton = $(".saveBtn");
let numericCurrentTime = parseInt(moment().format("H A"));
let notes = [];
currentDayPlaceholder.append(moment().format('dddd, MMMM Do'));
function timeBlocksColorDeterminator() {
for (let i = 0; i < timeInTimeBlocks.length; i++) {
let numericTimeinTimeBlock = parseInt($(timeInTimeBlocks[i]).text());
if ($(timeInTimeBlocks[i]).hasClass('pm')) {
numericTimeinTimeBlock += 12;
}
if (numericCurrentTime === numericTimeinTimeBlock) {
$(timeBlockInput[i]).addClass("present");
} else if (numericCurrentTime > numericTimeinTimeBlock) {
$(timeBlockInput[i]).addClass("past");
} else {
$(timeBlockInput[i]).addClass("future");
}
}
}
function appStart() {
notes = JSON.parse(localStorage.getItem("timeBlockNotes"));
for (let i = 0; i < timeBlockInput.length; i++) {
if (i === parseInt(notes[i].id)) {
timeBlockInput[i].value = notes[i].value;
}
}
}
appStart();
saveButton.on("click", function () {
console.log("click");
notes.push({
value: timeBlockInput[this.id].value,
id: this.id
})
localStorage.setItem("timeBlockNotes", JSON.stringify(notes));
})
timeBlocksColorDeterminator();
【问题讨论】:
-
乍一看,我会说你的笔记数组中有一个
undefined条目:[undefined]。当您尝试从中访问 id 时,notes[i] 会产生 undefined 并抛出。或者 timeBlockInput.length > notes.length. -
在控制台中打印 notes[i] 值,如 console.log(notes[i]);并检查 note[i] 中是否有属性 id
标签: javascript jquery arrays object