[英]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.