shuffle React 中的奇怪行为
strange behavior in shuffle React
在我的 React 应用中,我为 2 个不同的卡片组调用了 shuffle 2 次,但是 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
时,您都在修改并返回传递给函数的基础数组,因此任何指向先前调用结果的变量 [=14] =] 将反映最近洗牌的数组。
解决方法是在 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;
};
在我的 React 应用中,我为 2 个不同的卡片组调用了 shuffle 2 次,但是 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
时,您都在修改并返回传递给函数的基础数组,因此任何指向先前调用结果的变量 [=14] =] 将反映最近洗牌的数组。
解决方法是在 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;
};