gpt4 book ai didi

Javascript:未定义和 for 循环问题

转载 作者:行者123 更新时间:2023-12-03 10:03:35 25 4
gpt4 key购买 nike

我在定义变量时遇到了另一个问题。它一直说该变量未定义。打印它时,它使用数组“rl”并定位第一个字符串,然后打印它。它会重复执行此操作,直到将整个数组一一打印出来。当我将“rl[c]”(C 是正在打印的数组中的当前数字)更改为 rl[1] 或 rl[2] 时,它会将其打印出来。当我打印 c 时,它会打印出玩家的数量......什么?如果您能帮助我,我将非常感激。JavaScript:

var al;
var rl;
var bd;
function gp(){
players = document.getElementById("input").value;
if(isNaN(players)){
alert(players.toUpperCase() + "'s Players? Please Fix");
return;
}
if(players === " "){
alert("Please Define How Many People Are Playing!");
return;
}
if(players === ""){
alert("Please Define How Many People Are Playing!");
return;
}
if(players < 4){
alert("Sorry, You Need Atleast 4 Players To Play!");
return;
}
SA(players)
}
function SA(players){
var positions = ["Murderer", "Judge", "Innocent", "Innocent"]; //Pre-set positions
if(players == 5){
positions.push("Co-Judge");
}else if(players == 6){
positions.push("Innocent", "Co-Judge");
}else if(players == 7){
positions.push("Murderer-2!", "Innocent", "Co-Judge");
}
Randomize(players, positions)
}
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
function Randomize(players, positions){
rl = shuffle(positions);
al = positions.length;
confirm("You Have: " + al + " Players, Correct?");
return rl;
}
var counter;
var c;
function DJ(){
var bd = 0;
for(var c = 0; c < al + 1; c++){
if(counter == 0){
var tz = c.value;
document.getElementById("DS").innerHTML=("You Are A: " + rl[tz]);
document.getElementById("DJ").innerHTML=("Click To Clear!");
counter = 1;


}else{
document.getElementById("DS").innerHTML=("Click 'Display Your Job!'");
document.getElementById("DJ").innerHTML=("Display Your Job!");
counter = 0;
}
}
}

HTML:

<html>
<head>
<link href="Styles.css" type="text/css" rel="stylesheet">
<script src="Javascript.js" language="javascript" type="text/javascript"></script>
<title>Miji</title>
</head>
<body>
<h1 id="mt">~*~ Miji ~*~</h1>
<div id="GetPlayers">
<input maxlength="1" id="input"> <button id="gp" onclick="gp()">Start!</button>
<br/>
<br/>
<button id="DJ" onclick="DJ();">Display Your Job!</button>
<br/>
<span id="DS">1) Input Amount Of Players. 2)Click 'Display Your Job!'</span>
</div>
</body>
</html>

更新:tz = c.value 用于测试 c 是否被设置为字符串或其他内容...

最佳答案

问题在于您将 al 设置为 positions.length,然后循环到 al + 1。请记住,JavaScript 数组是基于 0 的。

以大小为 4 的数组为例,例如:

var myArray = [1,2,3,4];

您正在设置 al = myArray.length,即 4,然后循环到第一个小于 4 + 1 的值,即 4。但是,长度为 4 的数组具有最大索引为 3,因此当循环到达最后一次迭代并将 innerHTML 设置为 myArray[4] 时,结果是未定义的。

关于Javascript:未定义和 for 循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30472103/

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