Search code examples
javascriptarraysundefinedsplice

Splice Object from Array - undefined error


Within the code below contains a very simple question game (work-in-progress). So far, I've been able to have a "Rules" message appear through the onLoad function, "qDisplayLoad()". Next, the onClick function "qDisplayClick" runs anytime someone clicks, thus randomly pulling from the array (qArray).

My question: How do you remove (splice) the question chosen from the array once it has been shown? My goal is to not have the same question repeat twice. Within the code below, you will find my amateur attempt at "splice" (and it kind of works), but instead, the array pushes out "undefined".

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;
}


Solution

  • The error comes from this line qArray.splice(qArray,1); The splice method can't take an array as the first parameter:

    array.splice(index, howmany, item1, ....., itemX)
    
    • index Required.
    • howmany Optional.
    • item1, ..., itemX Optional. The new item(s) to be added to the array