我正在制作一个程序,可以对卡片组中的某些卡片进行洗牌,但不是全部。我要洗牌的值存储在数组toBeShuffled中。我的函数中运行着多个for循环,每个循环都从数组中选择元素而不进行替换。但是,似乎每次新的for循环运行toBeShuffled数组时,都会使用先前的for循环中删除的元素重新填充。
function redeal() {
shuffleCards();
for(let a=rowholder1; a<=12;a++){
let randomPos = Math.floor(Math.random()*toBeShuffled.length);
cards[a].style.order = toBeShuffled.splice(randomPos,1);
}
for(let b=rowholder2; b<=25;b++){
let randomPos = Math.floor(Math.random()*toBeShuffled.length);
cards[b].style.order = toBeShuffled.splice(randomPos,1);
}
for(let c=rowholder2; c<=38;c++){
let randomPos = Math.floor(Math.random()*toBeShuffled.length);
cards[c].style.order = toBeShuffled.splice(randomPos,1);
}
for(let d=rowholder2; d<=51;d++){
let randomPos = Math.floor(Math.random()*toBeShuffled.length);
cards[d].style.order = toBeShuffled.splice(randomPos,1);
}
}
function shuffleCards() {
for(let i=0; i<13;i++) {
if(cards[i].style.order != cards[i+1].style.order - 1) {
rowholder1 = i+1;
for(let j=i+1;j<14;j++){
toBeShuffled.push(j);
}break;
}
}
for(let k=13; k<26;k++) {
if(cards[k].style.order != cards[k+1].style.order - 1) {
rowholder2 = k+1;
for(let j=k+2;j<28;j++){
toBeShuffled.push(j)
}break;
}
}
for(let l=26; l<39;l++) {
if(cards[l].style.order != cards[l+1].style.order - 1) {
rowholder3 = l+1;
for(let j=l+3;j<42;j++){
toBeShuffled.push(j)
}break;
}
}
for(let m=39; m<52;m++) {
if(cards[m].style.order != cards[m+1].style.order - 1) {
rowholder4 = m+1;
for(let j=m+4;j<56;j++){
toBeShuffled.push(j)
} return toBeShuffled;
}
}
}
我使用多个for循环的原因是因为卡中有些索引我不想重新分配订单。