【发布时间】:2026-01-15 22:45:01
【问题描述】:
我正在做一个简单的项目,检查学生是否正在写在线日记。使用 userId 检查学生的进度。如果学生的 userId 没有出现在 API 调用类 API 返回的 JSON 中,则应在容器中附加一个段落,告诉学生他们还没有完成任何事情。
这是我正在使用的数据类型的示例。
data = [
{ "userId": 101, "pagesDone": "005" },
{ "userId": 102, "pagesDone": "010" },
{ "userId": 103, "pagesDone": "020"},
{ "userId": 104, "pagesDone": "015" }
]
现在假设我正在与用户 ID 为 106 的学生一起工作。该学生没有出现在 JSON 数据中,因为他们还没有开始研究期刊。
let currentUserId = 106;
// Student has not completed anything in their journal
let showStudentJournal = (data, currentUserId) => {
for (var index = 0; index < data.length; index++) {
if (currentUserId == data[index].userId) {
// I have figured out the code here, basically I append a progressBar to a container to show the student's progress
// I won't show the code here since that's not what we're focusing on.
//The thing I want to happen is, get a paragraph to appear if the student hasn't filled out any of the online journal yet
} else {
$("#progressContainer").append('<p>You have not yet started your online Journal</p>');
}
}
}
但是,函数最终运行了 4 次(因为数据中有 4 个学生)。所以这就是我得到的回报:
'<p>You have not yet started your online Journal</p>'
'<p>You have not yet started your online Journal</p>'
'<p>You have not yet started your online Journal</p>'
'<p>You have not yet started your online Journal</p>'
如何让错误消息只出现一次?
【问题讨论】:
-
使用标志来了解用户 id 是否在数组中可用,并根据标志在 for 循环之外添加您的附加语句。
-
不要使用
for循环使用find。如果不存在userid,则追加段落。
标签: javascript jquery function for-loop if-statement