如果变量存在...对象与变量,null与未定义

If variable exists.....object vs variable, null vs. undefined

本文关键字:变量 null 未定义 对象 存在 如果      更新时间:2023-09-26

这个脚本的第一部分似乎工作正常,它遍历每个文档,如果文档名称与特定的正则表达式模式匹配,它会为它提供一个特定的变量,以便稍后在脚本中使用。

然而,在脚本的最后,当我试图判断一个变量是否作为if语句的条件存在时,结果并不像预期的那样为true或false。我在这里做错了什么?

// iterate through all docs assigning variables to templates and art  
for (i = 0; i < documents.length; i++) {
  var curDoc = app.activeDocument = app.documents[i];
  var curDocNoExt = curDoc.name.split(".");
  var workingName = curDocNoExt[0];
  if (workingName.match(/^'d{5,6}$/) != null) {
    var frontArt = app.documents[i];
    var targetName = frontArt.name
  } else {
    if (workingName.match(/^'d{5,6}(b))$/) != null) {
      var backArt = app.documents[i];
      var backToggle = 1;
    } else {
      if (workingName.match(/^fkeep$/) != null) {
        var frontTemp = app.documents[i];
      } else {
        if (workingName.match(/^fxkeep$/) != null) {
          var frontSquare = app.documents[i];
        } else {
          if (workingName.match(/^bkeep$/) != null) {
            var backTemp = app.documents[i];
          } else {
            if (workingName.match(/^bxkeep$/) != null) {
              var backSquare = app.documents[i];
            }
          }
        }
      }
    }
  }
}
//use variables to do stuff!  
if (backArt != null) {
  app.activeDocument = backTemp;
  var namedBackTemp = backTemp.duplicate(targetName + "B");
}

在javascript中,undefined是false,因此您可以在if语句中使用如下变量:

var var1 = '', // can be anything
    var2; // this is an undefined var
if (var1){ // var1 has been initialized so this evaluates to true
  doSomething(); // this will execute
}
if (var2){ // var2 is undefined, so it evaluates as false
  doSomethingElse(); // this will not execute
}

然而,更好的做法是使用typeof,它返回对象类型的字符串:

var var1 = '';
var var2 = {};
typeof var1 == 'string';
typeof var2 == 'object';
typeof var3 == 'undefined';
if (typeof var1 !== 'undefined'){
  doSomething(); // this gets executed because var1 is a string
}

希望这能让你更好地理解