我想将 semiusedcards 的值设置为与 usedcards 相同。但是当我运行函数时:usedcards 得到更新而我没有设置不同的值。
代码:
const cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
const colors = ['hearts', 'clubs', 'diamonds', 'spade'];
let usedcards = [];
function randomcard(){
let semiusedcards = usedcards;
if(semiusedcards.length != 52){
let duplicate = false;
let random1 = Math.round(Math.random() * 3);
let random2 = Math.round(Math.random() * 12);
if(semiusedcards.length == 0){
semiusedcards.push({'color': colors[random1], 'card': cards[random2]})
}
else{
for(j = 0; j < semiusedcards.length; j++){
if(semiusedcards[j].color == colors[random1] && semiusedcards[j].card == cards[random2]){
duplicate = true
//console.log('duplicate');
}
}
if(duplicate == false){
semiusedcards.push({'color': colors[random1], 'card': cards[random2]})
//console.log('added');
}
else{
randomcard()
}
}
}
let number = semiusedcards.length - 1;
return semiusedcards[number];
}
最佳答案
您需要克隆数组列表:
let semiusedcards = [...usedcards];
这样您就可以创建一个包含相同条目的新列表。
否则你只需在 semiusedcards 变量中引用同一个列表
关于javascript - 我的变量更改了它设置为的变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59591394/