0

我的目标是使用脚本开发一个非常简单的“制作你自己的故事”游戏引擎。现在,这段代码足以开始故事,但在传递列表中的最终数组后会产生“未定义”。这令人沮丧,因为我确信我已经多次偶然发现了该解决方案,但我不知道该怎么做。我只应该为此使用基本的 JS,所以没有 jquery、php 等。我知道那里应该有一个 for 循环/变量计数器。

HTML:

<p id="story">Hello.</p>


<input name="NavButton" type="button" 
value="Start" 
onclick= "OnPress();" />

JS:

function OnPress()
{
document.getElementById("story").innerHTML=myArray[i++];
}


var myArray = new Array();
myArray[0] = "Welcome to the Dark Abyss.";
myArray[1] = "There's a fork in the road. What to do?";
myArray[2] = "The fox doesn't talk much.";
myArray[3] = "Thank Grozia! You survived.";

var i=myArray.indexOf(myArray[0]);
4

3 回答 3

0

您需要确保您提供的索引是有效的,即您不会到达数组的末尾。在这种情况下,检查就足够了:

function OnPress()
{
if(i < myArray.length) // check that i is valid
  document.getElementById("story").innerHTML=myArray[i++];
else
  i = 0; // reset i back to start
}
于 2013-06-16T22:18:41.190 回答
0

这是您正在寻找的简单迭代器。我写的是 onPress 而不是 OnPress。您不应该用大写字母编写方法名称。

var myArray = [
"Welcome to the Dark Abyss.",
"There's a fork in the road. What to do?",
"The fox doesn't talk much.",
"Thank Grozia! You survived."
];

var current = -1;

function onPress()
{
    current = current >= myArray.length -1 ? 0 : current+1;
    document.getElementById("story").innerHTML=myArray[current];
}
于 2013-06-16T22:26:00.287 回答
0

在两种情况下你会得到“未定义”:

  1. 不支持 Array.indexOf 的 IE。所以你总是得到“未定义”。
  2. 当 i 大于 4 时,会导致“Index out of range”错误,所以 myArray[i++] 返回“undefined”。

为了解决问题,您可以尝试:

  1. 在开始时将 i 设置为 0 或扩展 Array.prototype 以使 Array.indexOf 在 IE 中工作
  2. 每当我达到 4 时,将其重置为 0 或 myArray.indexOf(myArray[0])(soenke 和 BIOS 已经给了你答案)。或者你可以使用 i %= 4。

代码:

function OnPress() {
    i %= 4;
    document.getElementById("story").innerHTML = myArray[i++];
}

var myArray = new Array();
myArray[0] = "Welcome to the Dark Abyss.";
myArray[1] = "There's a fork in the road. What to do?";
myArray[2] = "The fox doesn't talk much.";
myArray[3] = "Thank Grozia! You survived.";

var i = 0;  

希望它有帮助。

于 2013-06-17T00:44:23.927 回答