[英]strange behavior in shuffle React
in my React app, I call shuffle 2 times for 2 different card sets but shuffle always gives 2 card sets the exact same result, can someone help me fix it? 在我的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 gives 2 card sets the same result until I run shuffleCards function again. shuffle会给2张卡片集相同的结果,直到我再次运行shuffleCards函数。 this is my shuffle function 这是我的随机播放功能
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
, and cards2
are all pointing to the same array in your example as JavaScript passes array by reference . cards
, cards1
,和cards2
都指向相同的阵列中的例子,如JavaScript 通过引用传递数组。
The result is that every time you call shuffle
, you are modifying and returning the underlying array that was passed to the function, and therefore any variable that was pointing to a result from previously calling shuffle
will reflect the most recently shuffled array. 结果是,每次调用shuffle
,您都在修改并返回传递给该函数的基础数组,因此,指向先前调用shuffle
的结果的任何变量都将反映最新的shuffled数组。
The fix is to create a copy of your array in shuffle
so that cards
, cards1
, and cards2
all point to different arrays: 解决方法是在创建您的数组的副本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.