繁体   English   中英

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

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

基本上我必须用 3category 创建一个测验。 每个有5个问题。 我必须将选定的类别问题从包含所有问题的数组中推送到这个新数组中。 我无法这样做。

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

}

usercategory = 来自用户的输入。 如果用户选择类别 1。如果 (1 == questionPool[1].category)(如果它与类别匹配)那么它将被推送。

这是我做不到的部分

好吧,根据您提供的信息,这里有一个主要问题 - return语句绝对是循环的捷径 - 所以即使您的其他一切都正确,您也只会得到第一个匹配的问题。 其余的将被 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;
                }
            }

}

有很多方法可以在这里完成您想做的事情。 例如,您可以像这样使用 javascript Array.filter方法

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

也许我没有正确理解你的问题,但你不能使用嵌套数组。 如果问题是事先分类的。

暂无
暂无

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

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