简体   繁体   中英

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

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

Thank you very much, Melchia.

Yes, you are correct! I was able to resolve this issue by updating the following:

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

Thank you, and happy new year!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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