首页 > 解决方案 > 如何从这个 JavaScript 输出中显示特定数量的问题?

问题描述

在以下脚本中,我如何显示 5 个问题中的特定数量。例如,我只想显示 3 个问题。

这是功能齐全的Codepen供参考。

有没有快速解决方法?

var $progressValue = 0;
var resultList=[];


const quizdata=[
      {
        question:"Characterized by skill at understanding and profiting by circumstances",
        options:["Prescient", "Analyst", "Diminution", "Shrewd"],
        answer:"Shrewd"
      },
      {
        question:"To refuse to acknowledge as one's own or as connected with oneself",
        options:["Prevalent", "Disown", "Squalid", "Employee"],
        answer:"Disown"
      },
      {
        question:"Not having the abilities desired or necessary for any purpose",
        options:["Incompetent", "Impoverish", "Coxswain", "Devious"],
        answer:"Incompetent"
      },
      {
        question:"Lizard that changes color in different situations",
        options:["Scruple", "Depredation", "Chameleon", "Whimsical"],
        answer:"Chameleon"
      },
      {
        question:"Having the title of an office without the obligations",
        options:["Reciprocal", "Unsullied", "Titular", "Inflated"],
        answer:"Titular"
      }
    ];

标签: javascript

解决方案


您可以像这样更改 generateQuestions 函数:

/*** Return shuffled question ***/
function generateQuestions(qtty = -1){
  var questions=shuffleArray(quizdata);    
  if (qtty > 0) questions = questions.slice(0, qtty);
  return questions;
}

这将使它收到一个可选参数,告诉它返回特定数量的问题。

您将不得不更改它的调用(它位于第 297 行附近的 $(document).ready() 上)以传递所需数量的问题。

您可以做的一件事是在隐藏输入中包含问题的数量。像那样:

<input type="hidden" id="QttyQuestions" value="3" />

然后,寻找generateQuestions()调用(你可以在你的代码中搜索“ questions=generateQuestions();”)并像这样改变它:

questions=generateQuestions($('#QttyQuestions').val());

推荐阅读