【问题标题】:Splice Object from Array - undefined error从数组拼接对象 - 未定义的错误
【发布时间】:2018-01-02 07:57:23
【问题描述】:

在下面的代码中包含一个非常简单的问题游戏(正在进行中)。到目前为止,我已经能够通过 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;
}

【问题讨论】:

标签: javascript arrays undefined splice


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    非常感谢你,梅尔基亚。

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

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

    谢谢你,新年快乐!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 1970-01-01
      • 2021-06-01
      • 2022-11-20
      • 2019-10-16
      • 1970-01-01
      相关资源
      最近更新 更多