繁体   English   中英

数组中的拼接对象-未定义错误

[英]Splice Object from Array - undefined error

下面的代码中包含一个非常简单的问题游戏(进行中的游戏)。 到目前为止,我已经能够通过onLoad函数“ qDisplayLoad()”显示“规则”消息。 接下来,只要有人单击,onClick函数“ qDisplayClick”就会运行,从而从数组(qArray)中随机提取。

我的问题:显示阵列后如何删除(拼接)从阵列中选择的问题? 我的目标是不要让同一问题重复两次。 在下面的代码中,您会发现我业余尝试过“拼接”(并且确实可行),但该数组将推出“未定义”。

 var qLoad = 0; var qArray = [ "Question 1", "Question 2", "Question 3", "Question 4", "Question 5" ]; var randomElement; /* The text "Rules" appears when the page loads */ function qDisplayLoad() { if (qLoad == 0) { randomElement = "Rules"; qLoad = 1; /* Changes qLoad to "1" from "0" so the array begins within the "qDisplayClick" function */ } document.getElementById("questions").innerHTML = randomElement; } /* A new question is pulled from the array everytime the mouse is clicked (up to a maximum of 5) */ function qDisplayClick() { var randomNumber = Math.floor(Math.random() * qArray.length); /* Questions are randomly chosen and rounded down from the array */ if (qLoad += 1 && !(qLoad == 7)) { qArray.splice(qArray,1); randomElement = qArray[randomNumber]; } else if (qLoad == 0) { randomElement = "Rules"; } if (qLoad == 7) { /* After the 5th question, text will appear for the pop up */ randomElement = "WIP - POP UP PLACEHOLDER"; } document.getElementById("questions").innerHTML = randomElement; } 

错误来自此行qArray.splice(qArray,1); splice方法不能将数组作为第一个参数:

array.splice(index, howmany, item1, ....., itemX)
  • 索引必填。
  • howmany可选。
  • item1,...,itemX可选。 要添加到数组中的新项目

非常感谢Melchia。

是的,你是对的! 我能够通过更新以下内容解决此问题:

 randomElement = qArray[randomNumber]; qArray.splice(randomNumber,1); 

谢谢,新年快乐!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM