【发布时间】:2020-03-04 17:07:38
【问题描述】:
我正在制作一个测验应用程序。除了对我的数组进行洗牌的功能外,一切都运行良好,因此每次的答案似乎都是随机的。这是代码。
shuffleArray() {
let array = this.state.answerArray;
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
获取和存储工作正常,但每当我调用 shuffleArray 函数时,我的原始数组 (answerArray) 也会像 shuffledArray 一样随机播放。
我在获取我的数据后在 setState 之后调用函数
this.setState(
{
qid: _id,
question: question,
correct_answer: correct_answer,
answerArray: [
correct_answer,
answer1 || " ",
answer2 || " ",
answer3 || " "
]
},
() => {
this.setState({
shuffledArray: this.shuffleArray()
});
}
);
知道为什么两个数组都洗牌吗?
【问题讨论】:
标签: javascript reactjs