使用If Else语句将字符串分配给变量

时间:2020-05-15 15:29:06

标签: javascript

对不起,这是一个非常基本的问题,但是我对Google脚本还不太熟悉,因此很难找到这些简单任务的答案。在这段代码中,我试图基于另一个变量将数字字符串设置为一个变量。 AppNaming是我要分配数字的变量。 AppType在代码的前面已经定义了,根据类型,我需要它仅包含变量AppNumber的一部分。根据AppType,AppNumber用逗号或斜杠分隔,因此使用indexOf部分。 var函数是否不允许使用语句?我需要根据AppType更改var AppNaming以便稍后在代码中命名文件。感谢您提供的所有帮助,如果这些问题令人讨厌,请再次表示抱歉;我还在学习。

function AutoFill(e) {

  // variables all defined earlier 

  //Naming code

  var AppNaming = if( AppType == '1' ){ 
    AppNumber.substring( 0, AppNumber.indexOf(","))
  }
  else if ( AppType == '2'){
    AppNumber.substring( 0, AppNumber.indexOf("/"))
  }
  else ( AppType == '3'){
    AppNumber.substring( 0, AppNumber.indexOf(",")) 

}

1 个答案:

答案 0 :(得分:1)

您只能将值分配给变量。不幸的是,if语句不是值,因此您不能说var a = if (...) { },但可以说var a = 3

if语句控制应用程序的流程。

var something = 20;
var a;
if (something > 20) {
  a = "this block runs if something is greater than 20";
} else if (something < 20) {
  a = "this block runs if something is less than 20";
} else {
  a = "this block runs otherwise";
}

// The value of 'a' is 'this block runs otherwise' at this point

因此在您的示例中,您可以将App.Number.substring(0, AppNumber.indexOf(",")分配给变量,因为该表达式将返回一个值。

I would recommend you to learn the basics of JavaScript.

相关问题