[英]Javascript Array not being filled properly
我在使数组正确填充方面遇到一些麻烦。 我试图将一副纸牌加载到阵列中,然后将其改组,这在最初可以正常运行,但是,在我检查是否有足够的纸牌后,阵列无法正确加载,并且其他所有功能或更少的休息时间。
这是相关的代码。 任何帮助将不胜感激。 谢谢!
var deck = {
//base deck before shuffle
baseDeck: ['d02', 'd03', 'd04', 'd05', 'd06', 'd07', 'd08', 'd09', 'd10', 'd11', 'd12', 'd13', 'd14', 'h02', 'h03', 'h04', 'h05', 'h06', 'h07', 'h08', 'h09', 'h10', 'h11', 'h12', 'h13', 'h14', 'c02', 'c03', 'c04', 'c05', 'c06', 'c07', 'c08', 'c09', 'c10', 'c11', 'c12', 'c13', 'c14', 's02', 's03', 's04', 's05', 's06', 's07', 's08', 's09', 's10', 's11', 's12', 's13', 's14'],
//Deck Shoe
shoe: [],
//pull deck #, return to shoe
shuffleDeck: function () {
this.shoe.length = 0;
this.shoe = this.baseDeck;
for (i = 0; i < this.shoe.length; i++) {
var randomPlace = Math.floor(Math.random() * 50) + 1;
var currentPlace = this.shoe[i];
this.shoe[i] = this.shoe[randomPlace];
this.shoe[randomPlace] = currentPlace;
}
}
}
var cardRetrieval = {
//return card vals
getCard: function (curHand) {
var q = curHand.push(deck.shoe.shift());
this.checkValue(curHand);
showCards(curHand, q);
if (deck.shoe.length <= 40) {
deck.shuffleDeck();
}
}
一切正常,直到底部的if语句检查热靴阵列中是否有40张以上的卡片。 但是,当它再次尝试重新洗牌时,它就会破裂。
问题是这样的:
this.shoe.length = 0;
this.shoe = this.baseDeck;
您没有将baseDeck
复制到shoe
。 相反,您将覆盖对您为shoe
创建的空Array的引用,并将其替换为对baseDeck
引用的同一Array的引用。
所以它在您第一次洗牌时就可以使用,因为this.shoe.length = 0
尚未影响baseDeck
。 但是当您第二次洗牌时,您正在破坏baseDeck
。 (基本上,在第一次洗牌时,您使用的是baseDeck
而不是其副本。)
更改为此:
this.shoe.length = 0;
this.shoe = this.baseDeck.slice(0);
这将每次都引用shoe
引用的baseDeck
副本。
您的随机数有2个问题,1)永远不会为0
牌组中的第一张牌,以及2)可能超过了阵列大小。 使用此代替:
var randomPlace = Math.floor(Math.random() * this.shoe.length);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.