比较二维数组和一维数组的值



我正在为一个类创建一个琐事游戏,我正在努力将二维数组的单个索引的所有值与另一个数组的单个索引的单个值进行比较。根据我有限的经验,我正在使用 if 语句来比较这些值。我一定错过了一个步骤,但我不确定如何解决它。我认为错误的代码行是$(".choice").on('click', function() {});

提前感谢您的任何帮助。

.JS:

window.onload = function() {
$('#start').html('<div class="text-center"><button type="button" class="btn btn-default">Start</button></div>');
};
var questionArray = ["This bands second album went platinum 5 times in the UK and double Platinum in the US.", "This band was formed in Australia and their first album, which had you Walking On A Dream, has sold over 3 million copies."];
var optionArray = [["Radio Head", "Gorillaz", "Coldplay", "Arctic Monkeys"], ["Empire Of The Sun", "M83", "MGMT", "Two Door Cinema Club"]];
var answerArray= ["Gorillaz", "Empire Of The Sun"];
var imageArray= ["http://cdn3.pitchfork.com/artists/1767/m.65d9c64d.jpg", "http://crowningmusic.com/storage/rA7GUFFoBCtT8Jg4L1tv.png", "", "", ""];
var count = 0;
var question = 0;
$("#start").on('click', function() {
$(this).css("display","none");
timer(
30000,
function(timeleft) { 
$('#timer').html(timeleft);
},
function() { 
// What happens after //
}
);
$("#question").html(questionArray[question]);
for (var j = 0; j < 4; j++) {
$("#options").append('<button class="choice">' + optionArray[question][j] + "</button>" + "<br>");
}
$(".choice").on('click', function() {
console.log('click');
console.log(answerArray[question])
if (optionArray[question] == answerArray[question]) {
console.log("Working");
}
});
// $("#holder").html("<img src=" + questionArray[count] + ">");
});
function nextQuestion() {
count++;
}
// Timer Function //
function timer(time,update,complete) {
var start = new Date().getTime();
var interval = setInterval(function() {
var now = time-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
}
else update(Math.floor(now/1000));
},100); // the smaller this number, the more accurate the timer will be
}

当您将问题的答案与正确答案进行比较时,您需要包含用户所选选项的索引。尝试这样的事情:

$("#question").html(questionArray[question]);
for (var j = 0; j < 4; j++) {
// Include an ID in the choice button
$("#options").append('<button class="choice" id="choice_' + j + '">' + optionArray[question][j] + "</button>" + "<br>");
}
$(".choice").on('click', function() {
console.log('click');
console.log(answerArray[question]);
// Get the index of the selected answer through the ID attribute
var selectedAnswerIndex = $(this).attr('id').substring("choice_".length);
if (optionArray[question][selectedAnswerIndex] === answerArray[question]) {
console.log("Working");
}
});

另一个不处理答案索引的选项可能如下所示:

$(".choice").on('click', function() {
console.log('click');
console.log(answerArray[question])
// Use the text content of the button to check the answer
if ($(this).text() === answerArray[question]) {
console.log("Working");
}
});

注意:这依赖于按钮仅包含标记之间可能的答案值这一事实。如果您在按钮内放置任何其他内容,则此解决方案将不起作用。

最新更新