gpt4 book ai didi

javascript - 未捕获的 TypeError : undefined is not a function, 在 for 循环中创建的对象

转载 作者:搜寻专家 更新时间:2023-11-01 05:12:13 25 4
gpt4 key购买 nike

我正在构建一个小型测验应用程序,用户可以在其中构建自己的测验,但在 for 循环中创建对象时遇到了问题。

这是问题对象的构造函数:

var question = function(questionNumber, question, choices, correctAnswer) {
this.questionNumber = questionNumber;
this.question = question;
this.choices = choices;
this.correctAnswer = correctAnswer; //The number stored here must be the location of the answer in the array

this.populateQuestions = function populateQuestions() {
var h2 = $('<h2>').append(this.question);
$('#quizSpace').append(h2);
for (var i = 0; i < choices.length; i++) {
//Create the input element
var radio = $('<input type="radio">').attr({value: choices[i], name: 'answer'});

//Insert the radio into the DOM
$('#quizSpace').append(radio);
radio.after('<br>');
radio.after(choices[i]);
}
};
allQuestions.push(this);
};

我有一堆动态生成的 HTML,然后我从中提取值并将它们放在一个新对象中,如下所示:

$('#buildQuiz').click(function() {
var questionLength = $('.question').length;
for ( var i = 1; i <= questionLength; i++ ) {
var questionTitle = $('#question' + i + ' .questionTitle').val();
var correctAnswer = $('#question' + i + ' .correctAnswer').val() - 1;
var inputChoices = [];
$('#question' + i + ' .choice').each(function(){
inputChoices.push($(this).val());
});

var question = new question(i, questionTitle, inputChoices, correctAnswer);
}
allQuestions[0].populateQuestions();
$('#questionBuilder').hide();
$('#quizWrapper').show();
});

但是,当我单击 #buildQuiz 按钮时,我收到错误消息:

Uncaught TypeError: undefined is not a function 

在这一行:

var question = new question(i, questionTitle, inputChoices, correctAnswer);

最佳答案

这是因为 var question = new question(i, questionTitle, inputChoices, correctAnswer); 这行在它的范围内创建了另一个变量 question 即在点击事件处理程序。由于变量提升,它被移动到范围(函数)的顶部,最终变成:

   $('#buildQuiz').click(function() {
var question; //undefined
...
...
//here question is not the one (constructor) in the outer scope but it is undefined in the inner scope.
question = new question(i, questionTitle, inputChoices, correctAnswer);

只需将变量名更改为其他名称并尝试。

     var qn = new question(i, questionTitle, inputChoices, correctAnswer);

或者为了避免此类问题,您可以使用 Pascalcase 命名您的构造函数,即

 var Question = function(questionNumber, question, choices, correctAnswer) {
.....

关于javascript - 未捕获的 TypeError : undefined is not a function, 在 for 循环中创建的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20620611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com