简体   繁体   English

在包含数组的数组中查找元素

[英]Find Element Inside an Array, inside a Containing Array

I have a Questions Array tht has two elements that are Player 1's questions and Player 2's questions.我有一个问题数组,它有两个元素,分别是玩家 1 的问题和玩家 2 的问题。 The questions are objects arranged like so:问题是这样排列的对象:

var tempQuestion = {
    qId: i,
    leftQ: leftQ,
    rightQ: rightQ,
    correctAnswer: correctAnswer,
    allAnswers: sortedAnswers,
    questionText: questionText
}

I want to access the whole question object and pull this out into another array of current questions (one for each player), so both players have the same progress but they don't override each others questions.我想访问整个问题对象并将其提取到另一个当前问题数组中(每个玩家一个),因此两个玩家都有相同的进度,但他们不会覆盖彼此的问题。 So I try to pull them out of the array with a find on the ID field (much like you would in a C# or VB MVC application).因此,我尝试通过在 ID 字段上查找将它们从数组中拉出(很像您在 C# 或 VB MVC 应用程序中所做的那样)。

for (j = 0; j < playerCount; j++) {
    // Pick a random question
    this.Questions.push(this.players[j].questions);
    var rand = this.Questions[j].length - 1;
    function findQ(q) { 
        return q.qId === rand;
    }
    this.CurrentQuestion[j] = this.Questions[j].find(findQ);
}

However this returns CurrentQuestion as a null value.但是,这将CurrentQuestion作为空值返回。

Debugging told me that this.Questions is populated, so there's no problem there and the player count is also populated so it's not that either.调试告诉我 this.Questions 已填充,因此那里没有问题,并且玩家数量也已填充,因此也不是那样。 And the this.CurrentQuestion[j] = this.Questions[j].find(findQ);this.CurrentQuestion[j] = this.Questions[j].find(findQ); line is the one that breaks the application with the error:行是用错误破坏应用程序的那一行:

this.CurrentQuestion is null this.CurrentQuestion 为空

The array this.CurrentQuestion must first exist before you can access it's elements数组this.CurrentQuestion必须首先存在才能访问它的元素

Before you start the loop add:在开始循环之前添加:

this.CurrentQuestion=[];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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