目前正在构建吊死人游戏,在我的情况下,有一个包含 6 个项目的数组。因此,在一个回合中,每个项目当然会显示一次,并且还请记住,不可能在同一轮中显示重复的项目。下面我试图编写完成这项工作的代码,不幸的是,这在我的情况下不起作用。我的代码的问题在于它会继续循环遍历数组,当涉及到最新索引时,它应该洗牌数组。但是我得到错误词是未定义的,如果
函数随机播放
正在被称为
let data = ['apple', 'boring', 'citrus', 'dopamine', 'earth'];
const randomWord = () => {
setArrayCount(arrayCount + 1);
console.log(arrayCount, data.length);
if(arrayCount > data.length) {
setArrayCount(0);
shuffle(data);
} else {
}
replaceLetter(data[arrayCount].word);
cleanWord();
}
const shuffle = (a) => {
// create copy or new array
let newArr = [].concat(a);
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[newArr[i], newArr[j]] = [newArr[j], newArr[i]];
}
console.log(newArr);
return newArr;
}
@frontend。请参阅我的代码:
const App = () => {
let data = ["apple", "boring", "citrus", "dopamine", "earth"];
const [wordArray, setWordArray] = useState([]);
const clearData = () => {
setWordArray([]);
return ["apple", "boring", "citrus", "dopamine", "earth"]
}
const randomElem = data => {
while (data.length > 0) {
const indexChoose = Math.floor(Math.random() * data.length);
wordArray.push(data[indexChoose]);
setWordArray(wordArray);
data.splice(indexChoose, 1);
}
data = clearData()
};
return (
<div className="App">
<button
onClick={() => {
randomElem(data);
console.log('result: ',wordArray);
}}
>
Change
</button>
<button
onClick={() => {
clearData();
console.log('result: ',wordArray);
}}
>
Clear
</button>
</div>
);
};