当我写这篇文章的时候,我假设第二个控制台日志是一个4的数组。我的印象是我的代码会占用谁然后将其连接到第一个console.log的数组2然后下一次迭代将是一个4的数组,因为它是concat。
let player1Hand = [];
function drawDeck(whom, whichDeck, howMany) {
whom = whom.concat(whichDeck.splice(0, howMany));
console.log(whom);
}
drawDeck(player1Hand, genericDeck, 2);
drawDeck(player1Hand, genericDeck, 2);
相反,控制台日志是第一个数组,然后第二个日志是一个单独的数组......我想我写这篇文章的时候,我自己橡皮擦了。
答案 0 :(得分:0)
let player1Hand = [];
function drawDeck(whom, whichDeck, howMany) {
whom = whom.concat(whichDeck.splice(0, howMany));
console.log(whom);
player1Hand = whom;
}
drawDeck(player1Hand, genericDeck, 2);
drawDeck(player1Hand, genericDeck, 2);
我只是橡皮筋自己...在函数内部是临时的我需要重新评估player1H的值,然后让它指出函数的范围。所以第二次运行时,player1Hand值已经改为第一次尝试...
抱歉。也许这会在某些时候帮助别人。
答案 1 :(得分:0)
whom = whom.concat(whichDeck.splice(0, howMany));
用新数组重写存储在局部变量whom
中的引用。它不会以任何方式更改传入的引用或外部变量。因此,playerHand1
不会改变。相反,你可以传播到Array.push
实际改变传递的数组:
whom.push(...whichDeck.splice(0, howMany));
或只返回新数组:
return whom.concat(whichDeck.splice(0, howMany));
然后将其存储在playerHand1
:
playerHand1 = drawDeck(playerHand1, genericDeck, 2);
答案 2 :(得分:0)
您遇到的问题是使用concat返回一个新数组,而不是将项添加到您已有的当前数组中。将其设置为旧值不会更新引用。所以你应该使用参考。
使用ES6,您可以使用点差运算符
const newItems = whichDeck.splice(0, howMany)
whom.push(...newItems);
或没有ES6,您可以使用
var newItems = whichDeck.splice(0, howMany)
whom.push.apply(whom, newItems)
let playerDeck1 = []
let playerDeck2 = []
let remainingCards = [1,2,3,4,5,6,7,8,9,
10,11,12,13,14,15,16,17,18,19,
20,21,22,23,24,25,26,27,28,29]
const deal = (playerDeck, pile, drawCount) => {
const newItems = pile.splice(0, drawCount) // remove top N cards from the deck
playerDeck.push(...newItems); // put them on the end of the players current hand
}
console.group("turn1")
deal(playerDeck1, remainingCards, 5) // 1,2,3,4,5
deal(playerDeck2, remainingCards, 5) // 6,7,8,9,10
console.log("player1", JSON.stringify(playerDeck1))
console.log("player2", JSON.stringify(playerDeck2))
console.groupEnd("turn1")
console.group("turn2")
deal(playerDeck1, remainingCards, 2) // 1,2,3,4,5 + 11,12
deal(playerDeck2, remainingCards, 2) // 6,7,8,9,10 + 13,14
console.log("player1", JSON.stringify(playerDeck1))
console.log("player2", JSON.stringify(playerDeck2))
console.groupEnd("turn2")
console.group("turn3")
deal(playerDeck1, remainingCards, 2) // 1,2,3,4,5,11,12 + 15,16
deal(playerDeck2, remainingCards, 2) // 6,7,8,9,10,13,14 + 17,18
console.log("player1", JSON.stringify(playerDeck1))
console.log("player2", JSON.stringify(playerDeck2))
console.groupEnd("turn3")