简体   繁体   中英

Why does it automatically loop?

I have a question about javascript.

At first, the result of the code below is "-1 Hold", but I'm wondering why does the part where I put mark ① automatically loops with the next arguments?

I was expecting that the function processes through of it and put the result with only one argument, then goes to the next arguments. So I expected "1 Bet", "1 Bet", "-1 Hold", "0 Hold", "-1 Hold" would be output as a result.

I couldn't find explanation about this since yesterday to now.. I'd be happy if somebody helps me.

* This is the URL of the task I'm talking about.

Here is the code.

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

Thank you.

If you are using dev console to test it, it is simple. Only last command return value is shown (Not last line).

You should do something like

console.log(cc(3));
console.log(cc(7));
console.log(cc("Q"));
console.log(cc(8));
console.log(cc("A"));  

You can see when you are passing cc("A") it is decrementing the value.

 var count = 0; //1-> function cc(card) { switch (card){ case 2: case 3: case 4: case 5: case 6: count++; 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(3)); console.log(cc(7)); console.log(cc("Q")); console.log(cc(8)); console.log(cc("A"));

you are returning a string, but not doing anything with it. maybe you meant to write it like this:

var result = cc(3);

also its not good programming to mix strings and numbers like you are doing. when you write a function cc(card), you should decide if card is a string or a number. It will work fine as you have it, but it's not good coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM