英文:
displaying random questions at onces using react
问题
我正在创建一个测验应用程序,其中包括一个包含五个问题的数组,但我希望这五个问题随机显示,但同时显示所有五个问题。
const randomQuestion = (array) => {
let random = array[Math.floor(Math.random() * array.length)]
return random
}
const [current, setCurrent] = useState(() => randomQuestion(questions));
英文:
i am creating a quiz app which has an array that includes five questions but i want the five questions to display randomly but all the 5 questions at the same time
const randomQuestion = (array) => {
let random = array[Math.floor(Math.random() * array.length)]
return random
}
const [current, setCurrent] = useState(() => randomQuestion(questions));
答案1
得分: 0
这是使用 array.sort
方法的示例。
array = ["Hello", "Hello2", "Hello3", "Hello4", "Hello5"];
let random = array.sort(() => Math.random() - 0.5);
console.log(random);
英文:
Here's one using the array.sort
method.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
array = ["Hello", "Hello2", "Hello3", "Hello4", "Hello5"];
let random = array.sort(() => Math.random() - 0.5);
console.log(random);
<!-- end snippet -->
答案2
得分: 0
Here is the translated code snippet:
const randomQuestion = (data) => {
return data.sort(() => (Math.random() > 0.5 ? 1 : -1));
};
console.log(randomQuestion([2, 3, 4, 56, 7]));
const [current, setCurrent] = useState(() => randomQuestion(questions))
Please note that the code itself is not translated, as you requested.
英文:
const randomQuestion = (data) => {
return data.sort(() => (Math.random() > 0.5 ? 1 : -1));
};
console.log(randomQuestion([2, 3, 4, 56, 7]));
const [current, setCurrent] = useState(() => randomQuestion(questions))
答案3
得分: 0
以下是您要翻译的代码部分:
const randomizeArray = (array) => {
const newArray = array.slice();
for (let i = newArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[newArray[i], newArray[j]] = [newArray[j], newArray[i]];
}
return newArray;
};
const questions = [
"问题 1",
"问题 2",
"问题 3",
"问题 4",
"问题 5"
];
const randomizedQuestions = randomizeArray(questions);
console.log(randomizedQuestions);
请注意,我将英文的 "Question" 翻译成了中文的 "问题"。
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const randomizeArray = (array) => {
const newArray = array.slice();
for (let i = newArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[newArray[i], newArray[j]] = [newArray[j], newArray[i]];
}
return newArray;
};
const questions = [
"Question 1",
"Question 2",
"Question 3",
"Question 4",
"Question 5"
];
const randomizedQuestions = randomizeArray(questions);
console.log(randomizedQuestions);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论