我正在编写一个接受数组作为参数的函数。然后,该函数应重新排列数组。如果满足特定条件(validMoveCounter <4),则该功能将在改组前根据可用的卡创建一个新阵列。否则,该函数将只对给定的数组进行洗牌。
我遇到的问题是,当我的函数的else语句运行时,数组会全局更改,这很好。但是,当main(如果我的函数的一部分运行)时,我会得到带有改组数组的输出,但如果稍后尝试在程序中调用该数组,则不会改组数组。
换句话说,我函数的else部分会全局更改数组,但是函数的if部分只会在本地更改数组。
function shuffle(array) {
if (validMoveCounter < 4) { //When no moves are left we need to reshuffle
array = [];
holder = []; //the holder will make an array of arrays which we will map into a 1d array
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 13; j++) {
if (board[i][j] !== board[i][j + 1] - 1) { //checks if two cards are consecutive in value
holder[i] = board[i].splice(j + 1, 12 - j + 1);
break;
}
}
}
console.log(holder);
for (let i = 0; i < 4; i++) {. // pushes the elements of holder into the 1d array
for(num of holder[i]) {
array.push(num);
}
}
for (let i = 0; i < array.length; i++) { // removes blanks from the deck
if (array[i] === 'X') {
array.splice(i, 1);
i--;
}
}
for (i = 0; i < array.length; i++) { //this is not changing the global deck!!
let p = array[i];
let j = Math.floor(Math.random() * array.length);
array[i] = array[j];
array[j] = p;
};
console.log(array);
} else {
for (i = 0; i < array.length; i++) {
let p = array[i];
let j = Math.floor(Math.random() * array.length);
array[i] = array[j];
array[j] = p;
};
console.log(array);
}
}