此脚本的第一部分似乎正常工作,它遍历每个文档,如果文档名称与特定的正则表达式模式匹配,它会为它提供一个特定的变量,以便稍后在脚本中使用。
但是,在脚本结束时,当我向我们尝试变量是否作为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");
}
答案 0 :(得分:0)
在javascript中undefined
是假的,所以你可以像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
}
希望这能让您更好地理解