it_is_a_literature it_is_a_literature - 2 months ago 9
Javascript Question

Why is there only one line as result for my js code?

Here is my code,the output confused me.

var count = 0;
function cc(card) {
switch (card){
case 2:
case 3:
case 4:
case 5:
case 6:
count ++;
break;
case 7:
case 8:
case 9:
break;
case 10:
case 'J':
case 'Q':
case 'K':
case 'A':
count --;
break;
}
if (count >0){
return count+" "+"Bet";
}
else{
return count+" "+"Hold";
}
}
cc(2);cc(3);


It result in
"2 Bet"
,why the output is not

"1 Bet"


"2 Bet"


In my opinion,
cc(2);
result in
"1 Bet"
,and
cc(3);
following
cc(2);
result in another
"2 Bet"
,so the result is obvious that two lines in the output

"1 Bet"


"2 Bet"


Why is there only one line as result for the js code?

"2 Bet"

Answer

You're just not printing the result. You're just seeing the output of the last function because you're probably running this in the browser console.

If you log each result, you can see that the code does what you expect.

var count = 0;

function cc(card) {
  switch (card) {
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
      count++;
      break;
    case 7:
    case 8:
    case 9:
      break;
    case 10:
    case 'J':
    case 'Q':
    case 'K':
    case 'A':
      count--;
      break;
  }
  if (count > 0) {
    return count + " " + "Bet";
  } else {
    return count + " " + "Hold";
  }
}
console.log(cc(2)); // 1 Bet
console.log(cc(3)); // 2 Bet