Tag Archives: JS Error

[Solved] JS Error: cannot set property xxx of undefined

case1

Error code

quizList[index] = currentQuiz;
quizList[index].learningItem = item;

Error content

Cannot read properties of undefined (reading 'learningItem')

Error reporting reason

currentQuiz object may be undefined, if you add the property learningItem to the undefined object quizList[index] dynamically, it will cause the error “cannot set property xxx of undefined”.

Solution:

quizList[index] = currentQuiz == undefined ?{} : currentQuiz;
quizList[index].learningItem = item;

Just judge whether the quizlist [index] is undefined

 

case2

Error code

quiz.finishedstudent.forEach(item => {
	if (item.score < 80) {
		errorNum++;
	}
})

Error content

Cannot read properties of undefined (reading 'forEach')

Solution:

if (quiz.finishedstudent != undefined) {
	quiz.finishedstudent.forEach(item => {
		if (item.score < 80) {
			errorNum++;
		}
	})
}