我正在使用JavaScript制作测验游戏。
我将问题和答案目的地存储在嵌套数组中。
以这样的格式
var questions = [
["QUESTION",
"CHOICE_1", "CHOICE_2","CHOICE_3",
"DEST_1", "DEST_2", "DEST_3"]
]
当我收到问题名称时,我将使用questions[n][0]
和第一选择目的地questions[0][4]
但在某些情况下,它返回Cannot read property 'x'
我想知道是什么原因以及如何解决这个问题。感谢
$('.quiz').hide();
$('.result').hide();
var questions = [
//1
["Click either button",
"Yes", "No", "",
"2", "2", ""],
//2
["You will have an error when clicking the third button",
"FIRST", "SECOND", "THIRD",
"3", "3", ""],
//3
["If it works it should show you this page",
"END OF ERROR DEMONSTRATION", "CLICK THIS WILL ALSO CRASH", "",
"", "", ""],
];
function start() {
$('.start').hide('400');
$('.quiz').show();
getQuestion(1);
}
function getQuestion(n) {
var n = n - 1;
var d1 = questions[n][4];
var d2 = questions[n][5];
var d3 = questions[n][6];
$('#d_txt').html(questions[n][0]);
$('#c1').html(questions[n][1]);
$('#c2').html(questions[n][2]);
//Hide choice 3 if not exist
if (questions[n][3] == "") {
$('#c3').hide();
} else {
$('#c3').show();
$('#c3').html(questions[n][3]);
}
$("#c1").click(function () { getQuestion(d1) });
$("#c2").click(function () { getQuestion(d2) });
$("#c3").click(function () { getQuestion(d3) });
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body style="background-color: #E9ECEF">
<div class="jumbotron start">
<h1 class="display-5">Simple JS Quiz</h1>
<p class="lead">Click start amd I will guide you through how this is error</p>
<hr class="my-4">
<a class="btn btn-success btn-lg btn-block" href="#" role="button" onClick="start()">Start!</a>
</div>
<div class="jumbotron quiz">
<h1 class="display-5">Question</h1>
<p class="lead"><span id="d_txt">DETAIL_TEXT</span></p>
<hr class="my-4">
<a class="btn btn-secondary btn-lg btn-block" id="c1" href="#" role="button">CHOICE_1_TEXT</a>
<a class="btn btn-secondary btn-lg btn-block" id="c2" href="#" role="button">CHOICE_2_TEXT</a>
<a class="btn btn-secondary btn-lg btn-block" id="c3" href="#" role="button">CHOICE_3_TEXT</a>
</div>
</body>
答案 0 :(得分:1)
考虑到提供的代码段,只要对THIRD
,END OF ERROR DEMONSTRATION
,CLICK THIS WILL ALSO CRASH
执行点击操作,相应地,目标值(例如d
)就会设置为""
和getQuestion(d)
被调用。此后,getQuestion
退出如下:
var n = n - 1; // evals to var n = "" - 1 => undefined
var d1 = questions[n][4]; // evals to var d1 = questions[undefined][4]
因此导致错误:Cannot read property '4' of undefined
希望有所帮助。此外,正如其他评论中所提到的,建议使用基于对象的方法而不是嵌套数组用于此类方案。