2017-06-14 34 views
0

我正在處理Freecodecamp問題,其中一個組件正在處理5張卡片的值,並將其與您分配的值進行比較,然後顯示基於這些卡的當前計數。基於卡組的值增加/減少Javascript計數,並返回準確的計數

因此,例如;

數字2,3,4,5和6的卡片應使計數增加1. 數字7,8和9的卡片不應該做任何事情。 卡10,J,Q,K,A應該減1計數。

所以,如果我給它5卡值,它應該加起來,並提供我的計數,根據卡的價值。

這是我的代碼(我知道它是馬虎,但試圖讓它更好);

var count = 0; 

function cc(card) { 
    // Only change code below this line 
    switch (card) { 
    case ("A"): 
     --count; } 
    switch (card) { 
    case ("2"): 
     ++count; } 
    switch (card) { 
    case ("3"): 
     ++count; } 
    switch (card) { 
    case ("4"): 
     ++count; } 
    switch (card) { 
    case ("5"): 
     ++count; } 
    switch (card) { 
    case ("6"): 
     ++count; } 
    switch (card) { 
    case ("7"): 
     } 
    switch (card) { 
    case ("8"): 
     } 
    switch (card) { 
    case ("9"): 
     } 
    switch (card) { 
    case ("10"): 
     --count; } 
    switch (card) { 
    case ("J"): 
     --count; } 
    switch (card) { 
    case ("Q"): 
     --count; } 
    switch (card) { 
    case ("K"): 
     --count; } 

return count; 
    // Only change code above this line 
} 

// Add/remove calls to test your function. 
// Note: Only the last will display 
cc(2); cc(3); cc(7); cc('K'); cc('A'); 

現在我試過使用返回計數; return ++ count;並返回 - 計數;這些都給了我不同的價值。我想我可能不會在底部引用cc的值,甚至根據正確的值來選擇計數,我想我可能只是對整套牌發出盲數。

任何幫助是超級讚賞。提前致謝。

回答

1

事情是這樣的:

var count = 0; 

function cc(card) {//or, with ES6: cc = (card) => { (no 'function' keyword required) 
switch (card) { 
    case ("A")://all of these 'fall through' until they hit break...be careful with this, and comment it in your code 
    case ("10"): 
    case ("J"): 
    case ("Q"): 
    case ("K"): 
     count -= 1;//or, count = count - 1 
     break;//break sends you out of the switch statement 
    case ("2")://same here 
    case ("3"): 
    case ("4"): 
    case ("5"): 
    case ("6"): 
     count += 1; 
     break; 
    //no need to do anything with 7, 8, 9 
} 
    return count; 
} 

您還可以添加一個「默認」的情況下到底比那些處理以外的值被髮送,但在這種情況下,你會做會count = count,這是沒有必要的。祝你好運!