我需要使用 splice 方法从数组中删除一个元素,但我不知道要删除的对象的索引。我尝试添加一个模仿索引的 ID 来删除该项目,但这似乎不起作用。
RandomiseNextQuestion: function(player1qs) {
// Pick a random question
this.Questions = player1qs;
var rand = Math.floor(Math.random() * player1qs.length);
function findQ(q) {
return q.qId === rand;
}
this.CurrentQuestion = player1qs.find(findQ);
if(this.CurrentQuestion) {
// Process question
}
// Remove that question so it can't be used again
this.Questions.splice(this.CurrentQuestion.qId, 1);
}
我也尝试过使用“rand”值来删除该项目,但这也不起作用。
最佳答案
您可以映射以查找元素的索引
var yourArray = ['bla','bloe','blie'];
var elementPos = yourArray.indexOf('bloe');
console.log(elementPos); // this will show the index of the element you want
yourArray.splice(elementPos,1); // this wil remove the element
console.log(yourArray);
我想你可以这样做
getRandomQuestion: function(playerQuestions) {
// Pick a random question and return question and index of question
this.questions = playerQuestions;
var rand = Math.floor(Math.random() * playerQuestions.length);
return this.questions[rand];
}
removeQuestion: function(question, playerQuestions){
playerQuestions.splice(playerQuestions.indexOf(question), 1);
return playerQuestions; // removes question and gives back the remaining questions
}
processQuestion: function(question){
//do something with the question
}
// you would call it like this
var questionsPlayer1 = ["the meaning of life", "the answer to everything"]
var question = getRandomQuestion(questionsPlayer1);
processQuestion(question);
removeQuestion(question, questionsPlayer1);
关于javascript - 在不知道索引的情况下从数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41853539/