如何使用onClick事件在div中显示不重复的随机文本



我的想法是制作一个问答卡游戏,当你点击一个按钮时,你会得到一个模态中的随机问题,所有这些都可以。我的问题是:我如何才能让已经出现的问题不再出现?例如,如果我得到问题3,它不会在整个游戏中再次出现。

const Arrayorange = [
{
question: "question 1",
reply: "Reply 1",
},
{
question: "question 2",
reply: "Reply 2",
},
{
question: "question 3",
reply: "Reply 3",
}
];
export function Orange() {
const [stateModal, changeStateModal] = useState(false)
const [index, setIndex] = useState(0);
function openandchange(){
changeOrange();
openModal();
}
function changeOrange() {
let newIndex = Math.floor(Math.random() * (Arrayorange.length - 0) + 0);
setIndex(newIndex);
}
function openModal(){
changeStateModal(!stateModal)
}
const audio = new Audio(cardsound)

function openwithsound(){
openandchange();
audio.play()
}
return (
<div>
<button className="btn" onClick={openwithsound}><IoIosBody/></button>
<ModalOrange
state={stateModal}
changeState={changeStateModal}
titulo="Question"

>
<Content>
<h1>{Arrayorange.[index].question}</h1>
<p>{Arrayorange.[index].reply}</p>
</Content>
</ModalOrange>
</div>
)
}

非常感谢您提前回答

好问题!

我想做的是,每次使用一个问题时,它都会从数组中删除,所以即使changeOrange((再次选择相同的数字,它也不能返回相同的问题。

你可能想要使用的方法是拼接

Arrayrange = arrayOrange.splice(newIndex, 1)

更多详细信息请点击此处:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

然后,您可以使用切片问题,而不是用选定的orangeArray索引在屏幕上驱动数据。

类似这样的东西:

function changeOrange() {
let newIndex = Math.floor(Math.random() * (Arrayorange.length - 0) + 0);
setQuestion(Arrayorange.slice(newIndex, 1)) //this gets the question and puts it in state
Arrayorange = Arrayorange.slice(newIndex, 1) // this ensures the same question can't be chosen ever again
}

编辑:已将拼接更改为切片

最新更新