【问题标题】:How can I select random N number of questions from array containing many questions?如何从包含许多问题的数组中选择随机 N 个问题?
【发布时间】:2019-07-30 15:34:00
【问题描述】:

我正在尝试使用 React 进行测验,显示来自 javascript 文件的 随机 100 个问题

这是javascript文件中的问题。

const quizQuestions = [
	
	{
		question: "Grand Central Terminal, Park Avenue, New York is the world's",
		options: ["largest railway station", "highest railway station", "longest railway station", "None of the above"],
		answer: "largest railway station"
	},
	{
		question: "Entomology is the science that studies",
		options: ["Behavior of human beings", "Insects", "The origin and history of technical and scientific terms", "The formation of rocks"],
		answer: "The origin and history of technical and scientific terms"
	},
	{
		question: "Eritrea, which became the 182nd member of the UN in 1993, is in the continent of",
		options: ["Asia", "Africa", "Europe", "Australia"],
		answer: "Africa"
	},
	{
		question: "Garampani sanctuary is located at",
		options: ["Junagarh, Gujarat", "Diphu, Assam", "Kohima, Nagaland", "Gangtok, Sikkim"],
		answer: "Diphu, Assam"
	},
	{
		question: "Hitler party which came into power in 1933 is known as",
		options: ["Labour Party", "Nazi Party", "Ku-Klux-Klan","Democratic Party"],
		answer: "Nazi Party"
	}
	
]

export default quizQuestions;

1.我需要 javascript 代码从上述文件中以随机顺序选择例如 3 个随机问题。类似地随机化选项而不重复问题

2。我想通过调用组件MCQ并将问题和选项作为道具传递来执行以下函数的次数与问题数一样多

function MCQ(props) {

	return(
		<div>
			<div>{props.question}</div>
			<div> 
				<input type="radio" name="answer" id=??? /><label for="???"> {props.options[0]}</label>
				<input type="radio" name="answer" id=??? /><label for="???"> {props.options[1]}</label>
				<input type="radio" name="answer" id=??? /><label for="???"> {props.options[2]}</label>
				<input type="radio" name="answer" id=??? /><label for="???"> {props.options[3]}</label>
			</div>
		</div>
		)
}

我应该提供什么 idname

谢谢你

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 欢迎来到 SO。请使用help centre 中的tour 查看how to ask a good question 以及该站点的on topic 是什么类型的问题。 SO 不是免费的代码编写服务 - 它适用于您尝试解决问题并遇到特定问题的地方

标签: javascript reactjs random


【解决方案1】:

要回答您的问题,您可以使用随机函数。只需在您的函数中添加以下代码行:

let ind= Math.floor(Math.random()*Math.floor(quiz.length));
console.log(ind);

console.log(quiz[ind].question)

然后你可以导出两个变量 index 和 quizQuestion 。然后就像你在 MCQ 函数中使用的那样使用

Quiz[index].options [0]

希望你能得到答案。希望你能得到答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 2021-12-03
    • 2010-12-03
    • 2016-11-12
    • 2019-11-30
    相关资源
    最近更新 更多