2016-04-21 33 views
0

我想在兩種情況下使用一種方法。一次有2個,一次有3個參數。當我用2個參數執行代碼時,它給了我:Mobile app - undefined,因爲chosenProgram參數是空的。當我想要在沒有- undefined的空參數輸入的情況下如何修改語句?當一個爲空時連接字符串不同

switchStatement: function(typeCode, chosenType, chosenProgram) { 

     switch (typeCode) { 
      case 1: 
       this.config.form__internet.find('input').val(chosenType + ' - ' + chosenProgram); 
       break; 
      case 2: 
       this.config.form__tv.find('input').val(chosenType + ' - ' + chosenProgram); 
       break; 
     } 
} 
+1

添加'chosenProgram = chosenProgram || '''在方法開始時。 – Tushar

+0

ES6:'function(typeCode,chosenType,chosenProgram =「」){' – Bergi

回答

1

如果你不想破折號,預先格式化字符串:

var result = chosenType + (chosenProgram ? (' - ' + chosenProgram): ""); 

,然後使用格式化字符串:

this.config.form__internet.find('input').val(result); 
0

您可以將chosenProgram值存儲在一個取決於其參數的不同var。

switchStatement: function(typeCode, chosenType, chosenProgram) { 
     var chosen = choseProgram === undefined ? "" : chosenProgram; 
     switch (typeCode) { 
      case 1: 
       this.config.form__internet.find('input').val(chosenType + ' - ' + chosen); 
       break; 
      case 2: 
       this.config.form__tv.find('input').val(chosenType + ' - ' + chosen); 
       break; 
     } 
} 
相關問題