在不知道索引的情况下从数组中删除对象

时间:2017-01-25 13:59:41

标签: javascript arrays

我需要从使用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'值删除项目,但这也不起作用。

2 个答案:

答案 0 :(得分:1)

使用单个命令可以做的就是filter

arr.filter((value) => value !== removeValue)

否则,如果你想继续使用你的数组(也就是可变的),你将不得不使用类似的东西:

const i = arr.indexOf('value')
arr.splice(i, 1)

答案 1 :(得分:1)

您可以映射以查找元素的索引

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