gpt4 book ai didi

javascript - 如何将琐事测验的答案随机放置在按钮槽中

转载 作者:行者123 更新时间:2023-12-02 20:52:00 25 4
gpt4 key购买 nike

所以我正在使用琐事游戏 API 来请求我正在编程的网络应用程序的琐事问题。我已经弄清楚如何随机化它,但我不知道如何不让它重复选项。

function useApiData(data){
let answers= [data.results[0].correct_answer, data.results[0].incorrect_answers[0], data.results[0].incorrect_answers[1], data.results[0].incorrect_answers[2]]

document.querySelector("#category").innerHTML = `Category: ${data.results[0].category}`
document.querySelector("#difficulty").innerHTML = `Difficulty: ${data.results[0].difficulty}`
document.querySelector("#question").innerHTML = `Question: ${data.results[0].question}`
document.querySelector("#answer1").innerHTML = `${answers[Math.floor(Math.random()*answers.length)]}`
document.querySelector("#answer2").innerHTML = `${answers[Math.floor(Math.random()*answers.length)]}`
document.querySelector("#answer3").innerHTML = `${answers[Math.floor(Math.random()*answers.length)]}`
document.querySelector("#answer4").innerHTML = `${answers[Math.floor(Math.random()*answers.length)]}`
}

最佳答案

因此,要使其按预期工作,您应该弹出数组中的每个选定项目,然后在现有项目之间做出新选择

应该是这样的:

function randomItemWithNoRepetition(array) {
let copy = Array.from(array); // Create a copy of input array
return function() {
if (copy.length < 1) { copy = Array.from(array); } // This line exist to create copy and make a new array from actual array whenever all possible options are selected once
const index = Math.floor(Math.random() * copy.length); // Select an index randomly
const item = copy[index]; // Get the index value
copy.splice(index, 1); // Remove selected element from copied array
return item; // Return selected element
};
}

const chooseFromArray = randomItemWithNoRepetition(['Foo', 'Bar', 'FU', 'FooBar' ]); // The input of this function should be the array of your answers. I just add dummy data as an input of function for more illustration.

document.querySelector("#answer1").innerHTML = `${chooseFromArray()}`; // "Bar"
document.querySelector("#answer2").innerHTML = `${chooseFromArray()}`; // "Foo"
document.querySelector("#answer3").innerHTML = `${chooseFromArray()}`; // "FU"
document.querySelector("#answer4").innerHTML = `${chooseFromArray()}`; // "FooBar"

关于javascript - 如何将琐事测验的答案随机放置在按钮槽中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61583221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com