簡體   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