[英]strange behavior in shuffle React
在我的React應用程序中,我為2個不同的卡集兩次調用shuffle,但是shuffle總是給出2個卡集的結果完全相同,有人可以幫我解決這個問題嗎?
class PairThemUp extends React.Component{
constructor(props){
super(props);
this.state={
cards1:[],
cards2:[],
}
}
shuffleCards=()=>{
const cards=this.props.selectedCards
const cards1=shuffle(cards)
const cards2=shuffle(cards)
this.setState({cards1, cards2})
const id1=cards1.map(c=>c.id)
const id2=cards2.map(c=>c.id)
console.log(id1, id2)
}
shuffle會給2張卡片集相同的結果,直到我再次運行shuffleCards函數。 這是我的隨機播放功能
export const shuffle=(a)=> {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
cards
, cards1
,和cards2
都指向相同的陣列中的例子,如JavaScript 通過引用傳遞數組。
結果是,每次調用shuffle
,您都在修改並返回傳遞給該函數的基礎數組,因此,指向先前調用shuffle
的結果的任何變量都將反映最新的shuffled數組。
解決方法是在創建您的數組的副本shuffle
,使cards
, cards1
和cards2
都指向不同的數組:
let shuffle = (a) => {
let newArr = [].concat(a); // create new array
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]];
}
return newArr;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.