如果我有一组卡片,如:
var deck = ["AH", "AS", "AD", "AC", "2H", "2S", "2D", "2C", "3H", "3S", "3D", "3C", "4H", "4S", "4D", "4C", "5H", "5S", "5D", "5C", "6H", "6S", "6D", "6C", "7H", "7S", "7D", "7C", "8H", "8S", "8D", "8C", "9H", "9S", "9D", "9C", "10H", "10S", "10D", "10C", "JH", "JS", "JD", "JC", "QH", "QS", "QD", "QC", "KH", "KS", "KD", "KC"];
将2个用户交易给用户:
var userHand = deck.splice([Math.floor(Math.random()*deck.length)+1], 1);
userHand.push(deck.splice([Math.floor(Math.random()*deck.length)+1], 1).join(""))
我得到类似的东西:
["5S", "2H"];
这两张牌都在牌外。
到目前为止一切顺利,但现在我想要计算用户拥有的点,在这种情况下它将是7.我需要一种方法来为图卡和Aces分配值。 我已经创建了一个函数,但它在某个地方出错了,我一直得到2:
function countPoints (){
for ( let i = 0; i < userHand.length; i++){
if ( userHand[i] == "AH" || "AS" || "AD" || "AC") {
userPoints += 1;
} else if ( userHand[i] == "2H" || "2S" || "2D" || "2C") {
userPoints += 2;
} else if ( userHand[i] == "3H" || "3S" || "3D" || "3C") {
userPoints += 3;
} else if ( userHand[i] == "4H" || "4S" || "4D" || "4C") {
userPoints += 4;
} else if ( userHand[i] == "5H" || "5S" || "5D" || "5C") {
userPoints += 5;
} else if ( userHand[i] == "6H" || "6S" || "6D" || "6C") {
userPoints += 6;
} else if ( userHand[i] == "7H" || "7S" || "7D" || "7C") {
userPoints += 7;
} else if ( userHand[i] == "8H" || "8S" || "8D" || "8C") {
userPoints += 8;
} else if ( userHand[i] == "9H" || "9S" || "9D" || "9C") {
userPoints += 9;
} else if ( userHand[i] == "10H" || "10S" || "10D" || "10C") {
userPoints += 10;
} else if ( userHand[i] == "JH" || "JS" || "JD" || "JC") {
userPoints += 10;
} else if ( userHand[i] == "QH" || "QS" || "QD" || "QC") {
userPoints += 10;
} else if ( userHand[i] == "KH" || "KS" || "KD" || "KC") {
userPoints += 10;
}
}
}
答案 0 :(得分:2)
userHand[i] == "AH" || "AS" || "AD" || "AC"
会产生真正的价值。您需要使用检查每个卡套装的相等性,而不仅仅是将它们组合在一起。
userHand[i] == "AH" || userHand[i] == "AS" ||
userHand[i] == "AD" || userHand[i] == "AC"
这里还有很大的改进空间,以保持干燥,但这解决了你的根本问题。请随意询问codereview.stackexchange.com