2015-08-30 30 views
0

我的問題除以三個問題:有沒有可能在javascript中添加切換語句的情況?

1.是否有可能?

2.如果是,我們可以使用默認值嗎?

3.或者可以在switch語句之外進行操作嗎?提問2

舉例:

switch(stuff) { 
    case 'something': 
     some event; 
     break; 
    case 'the case that could be add by the default element': 
     some event that could happen only after the code was executed 
    default: 
     magic code that would add another case element 
} 

舉例問題3:

switch(stuff) { 
    case 'something': 
     some event; 
     break; 
    case 'the case that could be add by the magic code': 
     some event that could happen only after the code was executed 
    default: 
     some default event 
} 

magic code that would be executed after the switch and that would add a case 
+1

你能描述一下你真正的問題嗎?因爲可能有比解決方案更好的解決方法。例如,您可以擁有檢查數組中每個項目的代碼,然後調用匹配函數,然後您的代碼可以隨時修改該數組。 – jfriend00

+0

這不是一個真正的問題......只是我想知道我能做什麼,不能在JS中做什麼:) –

回答

1

你真的不能編寫JavaScript代碼,這樣它會修改本身,而是你可以編寫一個開關語句,某些情況會在最初被忽略,然後「開啓」:

var enableCase = false; 

switch(true) { 
    case stuff === 'something': 
     // some code; 
     break; 
    case enableCase && stuff === 'the case not initially enabled': 
     // some code 
     break; 
    default: 
     // turn on previous case: 
     enableCase = true; 
     break; 
} 

說,我真的不建議這樣做。根據您正在嘗試解決的潛在問題,幾乎可以肯定有一個更明智的方法來實現這一點。也許用一個if/if else/else塊來測試在別處設置的標誌。

相關問題