我正在通过一个快速的二十一点游戏来学习javascript的一些基础知识,但我不明白为什么我的代码无法正常工作。显然我不了解JavaScript的基本原理
const types = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"J",
"Q",
"K",
"A"
];
const suite = ["Hearts", "Spades", "Clubs", "Diamonds"];
const draw = () => Math.floor(Math.random() * 52);
let cards = makeDeck(suite, types);
let score = 0;
//creates the card object
function Card(type, rank) {
this.type = type;
this.rank = rank;
}
//creates an array with every card
function makeDeck(suite, types) {
let cards = [];
let value = 0;
for (let i = 0; i < suite.length; i++) {
for (let j = 0; j < types.length; j++) {
cards.push(new Card(types[j], suite[i]));
}
}
return cards;
}
function determine(Card, score) {
let test = 11;
if (/^\d+$/.test(Card.type)) {
test = parseInt(Card.type);
console.log(test);
return test;
} else {
if (Card.type === "J" || "Q" || "K") {
test = 10;
return test;
} else {
if (score > 11) {
test = 2;
return test;
}
}
return test;
}
}
function game() {
let gameDeck = cards;
let card1 = gameDeck[draw()];
let card2 = gameDeck[draw()];
let card3 = gameDeck[draw()];
let card4 = gameDeck[draw()];
let scorePlayer = determine(card1, score) + determine(card2, score);
let scoreDealer = determine(card3, score) + determine(card4, score);
console.log(scoreDealer);
console.log(scorePlayer);
console.log(card1, card2, card3, card4);
}
game();
因此,我关心的是确定功能,该功能似乎无法按我预期的方式工作。我还没有实现真正的评分功能,但目前还不应该有太大的不同。我对let和const的使用是否有误?
答案 0 :(得分:1)
if (Card.type === "J" || "Q" || "K") {
test = 10;
return test;
}
无论“ Card.type”的值如何,该块始终为true。因为当Card.type不等于“ J”时,javascript会检查if("Q")
始终为true。同样,if("K")
也是如此。所有这些都是Javascript中的真实值。
Javascript有7个虚假条件,但所有其他条件均成立。
在浏览器控制台中尝试使用此代码段。
if("Q") {
console.log("This statement is true always")
}