簡體   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