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

标签 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”值来删除该项目,但这也不起作用。

最佳答案

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

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/

相关文章:

javascript - 将下拉菜单变成jquery slider

javascript - AJax 调用 Controller 从 JSP 页面传递数据

javascript - 使用数组中的名称创建新的(全局)对象

javascript - 在 javascript 中使用 map 更改数组

javascript - 两种方式绑定(bind)在具有嵌入范围的指令中不起作用

javascript - AngularJS $resource 将整个对象编码为 URL

ruby - 数组大小太大 - ruby

c - 如何显示和替换员工数据?

c - 编写一个函数 int caluculate_sum(int *a, int size) 计算数组中所有元素的总和

javascript - 使用 angular-chart.js 在条形图中手动设置 y 轴刻度