简体   繁体   English

我如何将数组 [i] 推送到另一个数组

[英]How do i push an array[i] to another array

Basically i have to create a quiz with 3category.基本上我必须用 3category 创建一个测验。 each with 5questions.每个有5个问题。 I would have to push the selected category-questions into this new array from the array with all the questions.我必须将选定的类别问题从包含所有问题的数组中推送到这个新数组中。 I am unable to do so.我无法这样做。

pushSelectedQuestion() {
    for (var i = 0; i < this.getNumberOfQuestion; i++) {
        if (usercategory == questionPool[i].category) {
            mcqSelected.push(questionPool[i])
            return mcqSelected;
        }
    }

}

usercategory = input from user. usercategory = 来自用户的输入。 if user chooses category 1. if (1 == questionPool[1].category) (if it matches the category) then it will be pushed.如果用户选择类别 1。如果 (1 == questionPool[1].category)(如果它与类别匹配)那么它将被推送。

This is the part which i cant do这是我做不到的部分

Well, from the information you've provided, there's one main issue here - the return statement is definitely shortcutting the loop - so even if you have everything else right, you'll only ever get the first matching question.好吧,根据您提供的信息,这里有一个主要问题 - return语句绝对是循环的捷径 - 所以即使您的其他一切都正确,您也只会得到第一个匹配的问题。 The rest will have been cut out by the return statement, which stops the function and returns the value.其余的将被 return 语句删除,它停止函数并返回值。

pushSelectedQuestion() {
    for (var i = 0; i < this.getNumberOfQuestion; i++) {
        if (usercategory == questionPool[i].category) {
            mcqSelected.push(questionPool[i])
           // the below line is causing this loop to end after the first time through the list. 
           // Remove it and then put a console.log(mcqSelected); 
           // here instead to see the value during each iteration of the loop.  
                    return mcqSelected;
                }
            }

}

There are a lot of ways to accomplish what you want to do here though.有很多方法可以在这里完成您想做的事情。 For example, you could just use the javascript Array.filter method like so例如,您可以像这样使用 javascript Array.filter方法

let selectedQuestions = questionPool.filter(question => question.category == userCategory)

Maybe I am not understanding your question correctly, but can't you use nested arrays.也许我没有正确理解你的问题,但你不能使用嵌套数组。 If the questions are categorized beforehand that is.如果问题是事先分类的。

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

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